'use client';

import { useEffect, useState, useRef, useCallback } from "react";
import Link from "next/link";
import { useParams, useRouter } from "next/navigation";
import { useSelector } from "react-redux";
import { RootState } from "@/lib/store/store";
import { getRelatedPosts } from "@/lib/api/client";

import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog";
import { Check } from "lucide-react";
import {
  ArrowLeft,
  Bookmark,
  Share2,
  MoreHorizontal,
  Calendar,
  Eye,
  Image as ImageIcon,
  ExternalLink,
  Flag,
  Zap,
  Loader2,
} from "lucide-react";
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
import { Button } from "@/components/ui/button";
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import Image from "next/image";
import {
  getPostById,
  likeDislike,
  savePostAPI,
  unSavePostAPI,
  addFlagReport,
} from "@/lib/api/client";
import { toast } from "sonner";

const BASE_URL = process.env.NEXT_PUBLIC_BASE_URL;

// Report reasons
const REPORT_REASONS = [
  "It's Spam",
  "Flag Objectionable",
  "Abusive Content"
];

// ========== SKELETON COMPONENTS ==========
function IdeaDetailSkeleton() {
  return (
    <div className="min-h-screen bg-background">
      <header className="sticky top-0 z-40 border-b border-border/50 glass">
        <div className="mx-auto max-w-5xl flex items-center justify-between px-4 py-4">
          <div className="flex items-center gap-2">
            <div className="h-5 w-5 bg-muted rounded animate-pulse"></div>
            <div className="h-4 w-24 bg-muted rounded animate-pulse"></div>
          </div>
          <div className="flex items-center gap-2">
            <div className="h-8 w-8 bg-muted rounded-lg animate-pulse"></div>
            <div className="h-6 w-24 bg-muted rounded animate-pulse"></div>
          </div>
          <div className="flex items-center gap-2">
            <div className="h-9 w-9 bg-muted rounded animate-pulse"></div>
            <div className="h-9 w-9 bg-muted rounded animate-pulse"></div>
          </div>
        </div>
      </header>
      <main className="mx-auto max-w-5xl px-4 py-8">
        <div className="grid lg:grid-cols-3 gap-8">
          <div className="lg:col-span-2 space-y-6">
            <div className="rounded-2xl glass glass-border p-6">
              <div className="flex items-start justify-between mb-6">
                <div className="flex items-center gap-4">
                  <div className="h-14 w-14 rounded-full bg-muted animate-pulse"></div>
                  <div>
                    <div className="h-5 w-32 bg-muted rounded animate-pulse mb-1"></div>
                    <div className="h-3 w-24 bg-muted rounded animate-pulse"></div>
                  </div>
                </div>
                <div className="h-6 w-20 bg-muted rounded-full animate-pulse"></div>
              </div>
              <div className="flex flex-wrap items-center gap-4 mb-6">
                <div className="h-4 w-24 bg-muted rounded animate-pulse"></div>
                <div className="h-4 w-16 bg-muted rounded animate-pulse"></div>
                <div className="h-6 w-16 bg-muted rounded-full animate-pulse"></div>
              </div>
              <div className="h-8 w-3/4 bg-muted rounded animate-pulse mb-4"></div>
              <div className="space-y-2">
                <div className="h-4 w-full bg-muted rounded animate-pulse"></div>
                <div className="h-4 w-5/6 bg-muted rounded animate-pulse"></div>
                <div className="h-4 w-4/6 bg-muted rounded animate-pulse"></div>
              </div>
            </div>
            <div className="rounded-2xl glass glass-border p-6">
              <div className="h-6 w-32 bg-muted rounded animate-pulse mb-4"></div>
              <div className="grid grid-cols-3 gap-3">
                {[1, 2, 3].map((i) => (
                  <div key={i} className="aspect-square bg-muted rounded-xl animate-pulse"></div>
                ))}
              </div>
            </div>
            <div className="rounded-2xl glass glass-border p-4">
              <div className="flex items-center justify-between">
                <div className="flex items-center gap-1">
                  <div className="h-10 w-16 bg-muted rounded animate-pulse"></div>
                  <div className="h-10 w-16 bg-muted rounded animate-pulse"></div>
                </div>
                <div className="flex items-center gap-1">
                  <div className="h-10 w-20 bg-muted rounded animate-pulse"></div>
                  <div className="h-10 w-20 bg-muted rounded animate-pulse"></div>
                </div>
              </div>
            </div>
            <div className="rounded-2xl glass glass-border p-6">
              <div className="flex items-center justify-between mb-4">
                <div className="h-6 w-32 bg-muted rounded animate-pulse"></div>
                <div className="h-8 w-16 bg-muted rounded animate-pulse"></div>
              </div>
              <div className="h-3 w-full bg-muted rounded-full animate-pulse"></div>
              <div className="h-3 w-48 bg-muted rounded animate-pulse mt-3"></div>
            </div>
          </div>
          <div className="space-y-6">
            <div className="rounded-2xl glass glass-border p-6">
              <div className="h-6 w-32 bg-muted rounded animate-pulse mb-4"></div>
              <div className="flex items-center gap-3 mb-4">
                <div className="h-12 w-12 rounded-full bg-muted animate-pulse"></div>
                <div>
                  <div className="h-5 w-28 bg-muted rounded animate-pulse mb-1"></div>
                  <div className="h-3 w-20 bg-muted rounded animate-pulse"></div>
                </div>
              </div>
              <div className="h-10 w-full bg-muted rounded animate-pulse"></div>
            </div>
            <div className="rounded-2xl glass glass-border p-6">
              <div className="h-6 w-32 bg-muted rounded animate-pulse mb-4"></div>
              <div className="space-y-4">
                {[1, 2, 3].map((i) => (
                  <div key={i} className="p-3 rounded-xl bg-secondary/30">
                    <div className="h-4 w-3/4 bg-muted rounded animate-pulse mb-2"></div>
                    <div className="flex items-center justify-between">
                      <div className="flex items-center gap-1">
                        <div className="h-4 w-4 rounded-full bg-muted animate-pulse"></div>
                        <div className="h-3 w-16 bg-muted rounded animate-pulse"></div>
                      </div>
                      <div className="h-3 w-8 bg-muted rounded animate-pulse"></div>
                    </div>
                  </div>
                ))}
              </div>
            </div>
          </div>
        </div>
      </main>
    </div>
  );
}

function RelatedIdeasSkeleton() {
  return (
    <div className="space-y-4">
      {[1, 2, 3].map((i) => (
        <div key={i} className="block p-3 rounded-xl bg-secondary/30 animate-pulse">
          <div className="h-4 w-3/4 bg-muted rounded mb-2"></div>
          <div className="flex items-center justify-between">
            <div className="flex items-center gap-1">
              <div className="h-4 w-4 rounded-full bg-muted"></div>
              <div className="h-3 w-16 bg-muted rounded"></div>
            </div>
            <div className="flex items-center gap-1">
              <div className="h-3 w-3 bg-muted rounded"></div>
              <div className="h-3 w-8 bg-muted rounded"></div>
            </div>
          </div>
        </div>
      ))}
    </div>
  );
}

function ThumbsUp({ className }: { className?: string }) {
  return (
    <svg className={className} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
      <path d="M14 9V5a3 3 0 0 0-3-3l-4 9v11h11.28a2 2 0 0 0 2-1.7l1.38-9a2 2 0 0 0-2-2.3zM7 22H4a2 2 0 0 1-2-2v-7a2 2 0 0 1 2-2h3" />
    </svg>
  );
}

export default function IdeaDetailPage() {
  const router = useRouter();
  const params = useParams();
  const ideaId = params?.id as string;

  const { accessToken, dynamicImages } = useSelector((state: RootState) => state.user);
  const securityKey = dynamicImages?.securityKey;

  // ✅ Refs for debouncing and request cancellation (same as IdeaFeed)
  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 [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [idea, setIdea] = useState<any>(null);

  // Like/Dislike/Save states
  const [liked, setLiked] = useState(false);
  const [disliked, setDisliked] = useState(false);
  const [saved, setSaved] = useState(false);
  const [likes, setLikes] = useState(0);
  const [dislikes, setDislikes] = useState(0);
  const [isSaving, setIsSaving] = useState(false);

  const [relatedIdeas, setRelatedIdeas] = useState<any[]>([]);
  const [loadingRelated, setLoadingRelated] = useState(false);

  // Report modal state
  const [showReportModal, setShowReportModal] = useState(false);
  const [selectedReason, setSelectedReason] = useState("");
  const [otherReason, setOtherReason] = useState("");
  const [isReporting, setIsReporting] = useState(false);
  const [reportSuccess, setReportSuccess] = useState(false);

  const [isDarkMode, setIsDarkMode] = useState(false);
  const [selectedImage, setSelectedImage] = useState<string | null>(null);

  // 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 = () => 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";

  useEffect(() => {
    if (idea && accessToken && idea.postCategory?._id) {
      fetchRelatedPosts();
    }
  }, [idea, accessToken]);

  const fetchRelatedPosts = async () => {
    if (!idea?.postCategory?._id) return;
    setLoadingRelated(true);
    try {
      const response = await getRelatedPosts(accessToken!, idea.postCategory._id, ideaId, 5, securityKey);
      if (response.success && response.data) {
        setRelatedIdeas(response.data);
      }
    } catch (error) {
      console.error("Error fetching related posts:", error);
    } finally {
      setLoadingRelated(false);
    }
  };

  useEffect(() => {
    if (ideaId && accessToken) {
      fetchIdea();
    }
  }, [ideaId, accessToken]);

  const fetchIdea = async () => {
    try {
      setLoading(true);
      const response = await getPostById(accessToken!, ideaId, securityKey);
      if (response.success && response.data) {
        const data = response.data;
        setIdea(data);
        setLiked(data.likeStatus === "like");
        setDisliked(data.likeStatus === "dislike");
        setSaved(data.bookmarked || false);
        setLikes(data.counts?.likes || 0);
        setDislikes(data.counts?.dislikes || 0);
      } else {
        setError(response.message || "Failed to load idea");
      }
    } catch (err: any) {
      console.error("Error fetching idea:", err);
      setError(err?.message || "Something went wrong");
    } finally {
      setLoading(false);
    }
  };

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

  // ✅ Debounced Like Handler (same as IdeaFeed)
  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;
    lastActionRef.current = "like";

    const wasLiked = liked;
    const wasDisliked = disliked;

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

    try {
      const result = await likeDislike(accessToken, ideaId, "like", securityKey);

      if (result.success) {
        const newLikeStatus = result.data.userReaction;
        setLiked(newLikeStatus === "like");
        setLikes(result.data.counts.likes);
        setDisliked(newLikeStatus === "dislike");
        setDislikes(result.data.counts.dislikes);
      } else {
        // Rollback
        if (wasLiked) {
          setLiked(true);
          setLikes(prev => prev + 1);
        } else {
          setLiked(false);
          setLikes(prev => prev - 1);
          if (wasDisliked) {
            setDisliked(true);
            setDislikes(prev => prev + 1);
          }
        }
        toast.error(result.message || "Could not like the post");
      }
    } catch (error: any) {
      if (error?.name === 'AbortError') return;
      // Rollback
      if (wasLiked) {
        setLiked(true);
        setLikes(prev => prev + 1);
      } else {
        setLiked(false);
        setLikes(prev => prev - 1);
        if (wasDisliked) {
          setDisliked(true);
          setDislikes(prev => prev + 1);
        }
      }
      toast.error("Could not like the post");
    } finally {
      isProcessingRef.current = false;
      lastActionRef.current = null;
    }
  }, [accessToken, ideaId, liked, disliked, securityKey]);

  // ✅ Debounced Dislike Handler (same as IdeaFeed)
  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;
    lastActionRef.current = "dislike";

    const wasLiked = liked;
    const wasDisliked = disliked;

    // 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, ideaId, "dislike", securityKey);

      if (result.success) {
        const newLikeStatus = result.data.userReaction;
        setLiked(newLikeStatus === "like");
        setLikes(result.data.counts.likes);
        setDisliked(newLikeStatus === "dislike");
        setDislikes(result.data.counts.dislikes);
      } else {
        // Rollback
        if (wasDisliked) {
          setDisliked(true);
          setDislikes(prev => prev + 1);
        } else {
          setDisliked(false);
          setDislikes(prev => prev - 1);
          if (wasLiked) {
            setLiked(true);
            setLikes(prev => prev + 1);
          }
        }
        toast.error(result.message || "Could not dislike the post");
      }
    } catch (error: any) {
      if (error?.name === 'AbortError') return;
      // Rollback
      if (wasDisliked) {
        setDisliked(true);
        setDislikes(prev => prev + 1);
      } else {
        setDisliked(false);
        setDislikes(prev => prev - 1);
        if (wasLiked) {
          setLiked(true);
          setLikes(prev => prev + 1);
        }
      }
      toast.error("Could not dislike the post");
    } finally {
      isProcessingRef.current = false;
      lastActionRef.current = null;
    }
  }, [accessToken, ideaId, liked, disliked, securityKey]);

  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, ideaId, securityKey);
      } else {
        result = await unSavePostAPI(accessToken, ideaId, securityKey);
      }

      if (result.success) {
        toast.success(wasSaved ? "Post unsaved" : "Post saved");
      } 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 handleShare = () => {
    const url = window.location.href;
    navigator.clipboard.writeText(url);
    toast.success("Link copied to clipboard!");
  };

  const handleReport = () => {
    setShowReportModal(true);
    setSelectedReason("");
    setOtherReason("");
  };

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

    const reportText = selectedReason === "Other" ? otherReason : selectedReason;
    if (!reportText.trim()) {
      toast.error("Please select a reason for reporting");
      return;
    }

    setIsReporting(true);
    try {
      const result = await addFlagReport(accessToken, ideaId, reportText, securityKey);
      if (result.success) {
        setReportSuccess(true);
        toast.success("Report submitted successfully. We'll review it shortly.");
        setTimeout(() => {
          setShowReportModal(false);
          setReportSuccess(false);
        }, 2000);
      } else {
        toast.error(result.message || "Failed to submit report");
      }
    } catch (error) {
      console.error("Error reporting post:", error);
      toast.error("Failed to submit report");
    } finally {
      setIsReporting(false);
    }
  };

  // Loading state with skeleton
  if (loading) {
    return <IdeaDetailSkeleton />;
  }

  if (error || !idea) {
    return (
      <div className="min-h-screen bg-background">
        <div className="flex flex-col items-center justify-center h-screen">
          <p className="text-red-500 mb-4">{error || "Idea not found"}</p>
          <Link href="/" className="text-primary hover:underline">
            Go back to feed
          </Link>
        </div>
      </div>
    );
  }

  const getUserProfileUrl = () => {
    const customer = idea.customerID;
    if (!customer) return "/home";
    const username = customer.userName || customer.username || customer.personalInfo?.userName;
    if (username) {
      return `/${username.startsWith('@') ? username : `@${username}`}`;
    }
    return "/home";
  };

  const getUserDisplayName = () => {
    const customer = idea.customerID;
    if (!customer) return "Unknown User";
    return customer.fullName || customer.name || customer.displayName ||
           customer.businessName || customer.personalInfo?.fullName ||
           customer.organization?.name || "Unknown User";
  };

  const getUserHandle = () => {
    const customer = idea.customerID;
    if (!customer) return "@user";
    return customer.userName || customer.username || customer.personalInfo?.userName ||
           `@${customer.email?.split('@')[0] || 'user'}`;
  };

  const getUserTypeLabel = () => {
    const customer = idea.customerID;
    if (!customer) return "Creator";
    if (customer.userType === "business" || customer.isBusinessUser === true || 
        customer.accountType === "business" || customer.role === "business") {
      return "Business";
    }
    if (customer.userType === "investor" || customer.isInvestor === true ||
        customer.accountType === "investor") {
      return "Investor";
    }
    return "Innovator";
  };

  const getIdeasCount = () => {
    const customer = idea.customerID;
    if (!customer) return 0;
    return customer.totalPosts || customer.postsCount || customer.ideasCount ||
           customer.totalIdeas || customer.stats?.totalPosts || customer.stats?.postsCount || 0;
  };

  const getUserAvatar = () => {
    const customer = idea.customerID;
    if (!customer) return undefined;
    return customer.imageURL || customer.avatar || customer.personalInfo?.imageURL || undefined;
  };

  const ideasCount = getIdeasCount();
  const userDisplayName = getUserDisplayName();
  const userHandle = getUserHandle();
  const userAvatar = getUserAvatar();
  const userTypeLabel = getUserTypeLabel();

  return (
    <div className="min-h-screen bg-background">
      {/* Top Navigation Bar */}
      <header className="sticky top-0 z-40 border-b border-border/50 glass">
        <div className="mx-auto max-w-5xl flex items-center justify-between px-4 py-4">
          <Link href="/" className="flex items-center gap-2 text-muted-foreground hover:text-foreground transition-colors">
            <ArrowLeft className="h-5 w-5" />
            <span className="font-medium">Back to Feed</span>
          </Link>
          <Link href="/" className="flex items-center gap-2">
            {dynamicImages?.headerLogo ? (
              <Image src={`${BASE_URL}/${dynamicImages.headerLogo}`} alt={dynamicImages?.title || "CheckUrIdea"} width={36} height={36} className="h-9 w-auto object-contain dark:brightness-0 dark:invert" priority />
            ) : (
              <div className="flex h-8 w-8 items-center justify-center rounded-lg bg-primary text-primary-foreground">
                <Zap className="h-4 w-4" />
              </div>
            )}

          

          </Link>
          <div className="flex items-center gap-2">
            {/* <Button variant="ghost" size="icon" onClick={handleShare} className="text-muted-foreground cursor-pointer">
              <Share2 className="h-5 w-5" />
            </Button> */}
            <DropdownMenu>
              <DropdownMenuTrigger asChild>
                <Button variant="ghost" size="icon" className="text-muted-foreground cursor-pointer">
                  <MoreHorizontal className="h-5 w-5" />
                </Button>
              </DropdownMenuTrigger>
              <DropdownMenuContent align="end" className="glass glass-border">
                <DropdownMenuItem onClick={handleReport} className="gap-2">
                  <Flag className="h-4 w-4" />
                  Report Idea
                </DropdownMenuItem>
                <DropdownMenuItem onClick={handleShare} className="gap-2">
                  <ExternalLink className="h-4 w-4" />
                  Copy Link
                </DropdownMenuItem>
              </DropdownMenuContent>
            </DropdownMenu>
          </div>
        </div>
      </header>

      <main className="mx-auto max-w-5xl px-4 py-8">
        <div className="grid lg:grid-cols-3 gap-8">
          {/* Main Content */}
          <div className="lg:col-span-2 space-y-6">
            {/* Author Info */}
            <div className="rounded-2xl glass glass-border p-6">
              <div className="flex items-start justify-between mb-6">
                <Link href={getUserProfileUrl()} className="flex items-center gap-4 group">
                  <Avatar className="h-14 w-14 ring-2 ring-primary/20">
                    <AvatarImage src={userAvatar ? `${BASE_URL}/uploads/${userAvatar}` : undefined} />
                    <AvatarFallback className="bg-primary/20 text-primary text-lg font-bold">
                      {userDisplayName.split(" ").map((n) => n[0]).join("").substring(0, 2).toUpperCase() || "U"}
                    </AvatarFallback>
                  </Avatar>
                  <div>
                    <div className="flex items-center gap-2">
                      <h3 className="font-bold text-foreground group-hover:text-primary transition-colors">{userDisplayName}</h3>
                      {idea.customerID?.isVerified && (
                        <div className="flex h-5 w-5 items-center justify-center rounded-full bg-primary">
                          <svg className="h-3 w-3 text-primary-foreground" fill="currentColor" viewBox="0 0 20 20">
                            <path d="M16.707 5.293a1 1 0 010 1.414l-8 8a1 1 0 01-1.414 0l-4-4a1 1 0 011.414-1.414L8 12.586l7.293-7.293a1 1 0 011.414 0z" />
                          </svg>
                        </div>
                      )}
                    </div>
                    <p className="text-sm text-muted-foreground">{userHandle}</p>
                  </div>
                </Link>
                <span className="rounded-full bg-primary/10 px-3 py-1 text-xs font-medium text-primary capitalize">{userTypeLabel}</span>
              </div>

              {/* Meta Info */}
              <div className="flex flex-wrap items-center gap-4 text-sm text-muted-foreground mb-6">
                <div className="flex items-center gap-1.5">
                  <Calendar className="h-4 w-4" />
                  {idea.createdAt ? new Date(idea.createdAt).toLocaleDateString("en-US", { month: "long", day: "numeric", year: "numeric" }) : "Unknown date"}
                </div>
                <div className="flex items-center gap-1.5">
                  <Eye className="h-4 w-4" />
                  {idea.views?.toLocaleString() || 0} views
                </div>
                <div className="rounded-full bg-secondary px-3 py-1 text-xs font-medium">
                  {idea.postCategory?.mainCategoryName || "General"}
                </div>
              </div>

              {/* Title */}
              <h1 className="text-2xl font-bold text-foreground mb-6 text-balance">
                {idea.title || idea.description?.slice(0, 100) || "Untitled Idea"}
              </h1>

              {/* Tags */}
              <div className="flex flex-wrap gap-2 mt-6 pt-6 border-t border-border/50">
                {idea.postCategory?.mainCategoryName ? (
                  <span className="rounded-full bg-secondary/50 px-3 py-1 text-xs font-medium text-muted-foreground">
                    #{idea.postCategory.mainCategoryName}
                  </span>
                ) : (
                  <span className="rounded-full bg-secondary/50 px-3 py-1 text-xs font-medium text-muted-foreground">#Idea</span>
                )}
              </div>
            </div>

            {/* Attachments */}
            <div className="rounded-2xl glass glass-border p-6">
              <h3 className="font-bold text-foreground mb-4">Attachments</h3>
              {idea.media && idea.media.length > 0 ? (
                <div className={`grid gap-3 ${idea.media.length === 1 ? "grid-cols-1" : idea.media.length === 2 ? "grid-cols-2" : "grid-cols-2 md:grid-cols-3"}`}>
                  {idea.media.slice(0, 6).map((media: any, idx: number) => (
                    <div key={idx} className="relative rounded-xl cursor-pointer overflow-hidden bg-white flex items-center justify-center h-48">
                      {media.type === "image" ? (
                        <img src={`${BASE_URL}/uploads/${media.url}`} alt={media.name || `Attachment ${idx + 1}`} className="max-h-full max-w-full object-contain transition-transform duration-300" onClick={() => setSelectedImage(`${BASE_URL}/uploads/${media.url}`)} />
                      ) : 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-black/40">
                            <div className="flex h-10 w-10 items-center justify-center rounded-full bg-primary/90">
                              <svg className="h-5 w-5 ml-0.5 text-white" viewBox="0 0 24 24" fill="currentColor"><path d="M8 5v14l11-7z" /></svg>
                            </div>
                          </div>
                        </div>
                      ) : (
                        <div className="flex items-center justify-center w-full h-full bg-secondary">
                          <svg className="h-8 w-8 text-muted-foreground" 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" />
                          </svg>
                        </div>
                      )}
                      {idea.media.length > 6 && idx === 5 && (
                        <div className="absolute inset-0 bg-black/60 flex items-center justify-center">
                          <span className="text-lg font-bold text-white">+{idea.media.length - 6}</span>
                        </div>
                      )}
                    </div>
                  ))}
                </div>
              ) : (
                <div className="grid sm:grid-cols-3 gap-4">
                  <div className="rounded-xl bg-secondary/30 p-4 flex flex-col items-center gap-3">
                    <div className="w-12 h-12 rounded-xl bg-primary/10 flex items-center justify-center">
                      <ImageIcon className="h-6 w-6 text-primary" />
                    </div>
                    <span className="text-xs text-muted-foreground text-center">No attachments</span>
                  </div>
                </div>
              )}
            </div>

            {/* ✅ Actions - Same as IdeaFeed */}
            <div className="rounded-2xl glass glass-border p-4">
              <div className="flex items-center justify-between">
                <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 ? "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 className="font-semibold">{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 ? "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 className="font-semibold">{dislikes}</span>
                  </button>
                </div>
                <div className="flex items-center gap-1">
                  <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" : ""}`} />
                  </button>
                  <button onClick={handleShare} className="flex h-9 w-9 cursor-pointer items-center justify-center rounded-lg text-muted-foreground hover:bg-secondary hover:text-foreground transition-all">
                    <Share2 className="h-5 w-5" />
                  </button>
                </div>
              </div>
            </div>

            {/* AI Score */}
            <div className="rounded-2xl glass glass-border p-6 opacity-80">
              <div className="flex items-center justify-between mb-4">
                <h3 className="font-bold text-muted-foreground">AI Analysis Score</h3>
                <div className="flex items-center gap-2">
                  <Zap className="h-5 w-5 text-muted-foreground" />
                  <span className="text-lg font-semibold text-muted-foreground">Coming Soon</span>
                </div>
              </div>
              <div className="w-full h-3 rounded-full bg-secondary/40 overflow-hidden">
                <div className="h-full bg-secondary/30 rounded-full" />
              </div>
              <p className="text-xs text-muted-foreground mt-3">Based on market viability, innovation score, and execution potential</p>
            </div>
          </div>

          {/* Sidebar */}
          <div className="space-y-6">
            {/* Author Card */}
            <div className="rounded-2xl glass glass-border p-6">
              <h3 className="font-bold text-foreground mb-4">About the Creator</h3>
              <div className="flex items-center gap-3 mb-4">
                <Avatar className="h-12 w-12">
                  <AvatarImage src={userAvatar ? `${BASE_URL}/uploads/${userAvatar}` : undefined} />
                  <AvatarFallback className="bg-primary/20 text-primary font-bold">
                    {userDisplayName.split(" ").map((n) => n[0]).join("").substring(0, 2).toUpperCase() || "U"}
                  </AvatarFallback>
                </Avatar>
                <div>
                  <p className="font-semibold text-foreground">{userDisplayName}</p>
                  <p className="text-xs text-muted-foreground">{ideasCount} {ideasCount === 1 ? "idea posted" : "ideas posted"}</p>
                </div>
              </div>
              <Link href={getUserProfileUrl()}>
                <Button className="w-full hover:dark:border-white hover:dark:text-white cursor-pointer" variant="outline">
                  View Profile
                </Button>
              </Link>
            </div>

            {/* Related Ideas */}
            <div className="rounded-2xl glass glass-border p-6">
              <h3 className="font-bold text-foreground mb-4">Related Ideas</h3>
              {loadingRelated ? (
                <RelatedIdeasSkeleton />
              ) : relatedIdeas.length > 0 ? (
                <div className="space-y-4">
                  {relatedIdeas.map((ideaItem) => (
                    <Link key={ideaItem.id || ideaItem._id} href={`/idea/${ideaItem.id || ideaItem._id}`} className="block p-3 rounded-xl bg-secondary/30 hover:bg-secondary/50 transition-colors">
                      <h4 className="font-medium text-foreground text-sm mb-2 line-clamp-2">
                        {ideaItem.title || ideaItem.description?.slice(0, 50)}
                      </h4>
                      <div className="flex items-center justify-between text-xs text-muted-foreground">
                        <div className="flex items-center gap-1">
                          <Avatar className="h-4 w-4">
                            <AvatarImage src={ideaItem.authorImage ? `${BASE_URL}/uploads/${ideaItem.authorImage}` : undefined} />
                            <AvatarFallback className="text-[10px]">{ideaItem.author?.[0] || "U"}</AvatarFallback>
                          </Avatar>
                          <span>{ideaItem.author || "Unknown"}</span>
                        </div>
                        <span className="flex items-center gap-1">
                          <ThumbsUp className="h-3 w-3" />
                          {ideaItem.likes || 0}
                        </span>
                      </div>
                    </Link>
                  ))}
                </div>
              ) : (
                <div className="text-center py-6">
                  <p className="text-sm text-muted-foreground">No related ideas found in this category.</p>
                </div>
              )}
            </div>
          </div>
        </div>
      </main>

      {/* Report Modal */}
      <Dialog open={showReportModal} onOpenChange={setShowReportModal}>
        <DialogContent className="sm:max-w-md glass glass-border">
          <DialogHeader>
            <DialogTitle>Report this idea</DialogTitle>
            <DialogDescription>Please let us know why you're reporting this content.</DialogDescription>
          </DialogHeader>
          {reportSuccess ? (
            <div className="flex flex-col items-center justify-center py-8">
              <div className="flex h-12 w-12 items-center justify-center rounded-full bg-green-500/10">
                <Check className="h-6 w-6 text-green-500" />
              </div>
              <p className="mt-4 text-center text-sm text-foreground font-medium">Report submitted successfully!</p>
              <p className="mt-1 text-center text-xs text-muted-foreground">We'll review your report and take appropriate action.</p>
            </div>
          ) : (
            <div className="flex flex-col gap-4 py-4">
              <div className="space-y-2">
                {REPORT_REASONS.map((reason) => (
                  <label key={reason} className="flex items-start gap-3 cursor-pointer p-2 rounded-lg hover:bg-secondary/50 transition-colors">
                    <input type="radio" name="reportReason" value={reason} checked={selectedReason === reason} onChange={(e) => setSelectedReason(e.target.value)} className="mt-1 h-4 w-4 text-destructive focus:ring-destructive" />
                    <span className="text-sm text-foreground">{reason}</span>
                  </label>
                ))}
              </div>
              {selectedReason === "Other" && (
                <textarea value={otherReason} onChange={(e) => setOtherReason(e.target.value)} placeholder="Please provide more details..." rows={3} className="w-full rounded-lg bg-secondary/30 border border-border/50 px-3 py-2 text-sm text-foreground placeholder:text-muted-foreground focus:outline-none focus:ring-2 focus:ring-destructive/50 resize-none" />
              )}
              <div className="flex justify-end gap-2 mt-2">
                <button onClick={() => setShowReportModal(false)} className="px-4 py-2 cursor-pointer rounded-lg text-sm font-medium text-muted-foreground hover:bg-secondary transition-colors">Cancel</button>
                <button onClick={submitReport} disabled={isReporting || (!selectedReason && !otherReason)} className="px-4 cursor-pointer py-2 rounded-lg text-sm font-medium bg-primary text-primary-foreground hover:bg-primary/90 disabled:opacity-50 disabled:cursor-not-allowed transition-colors flex items-center gap-2">
                  {isReporting && <Loader2 className="h-4 w-4 animate-spin" />}
                  Submit Report
                </button>
              </div>
            </div>
          )}
        </DialogContent>
      </Dialog>

      {/* Image Preview Modal */}
      {selectedImage && (
        <div className="fixed inset-0 z-50 bg-black/80 flex items-center justify-center p-4" onClick={() => setSelectedImage(null)}>
          <div className="relative max-w-4xl w-full" onClick={(e) => e.stopPropagation()}>
            <button onClick={() => setSelectedImage(null)} className="absolute -top-10 right-0 text-white bg-black/50 rounded-full p-2 hover:bg-black/70 transition-colors cursor-pointer">✕</button>
            <img src={selectedImage} alt="Preview" className="w-full max-h-[80vh] object-contain rounded-lg" />
          </div>
        </div>
      )}
    </div>
  );
}