"use client"

import { useState, useEffect, useRef} from "react"
import { useParams, useRouter, usePathname } from "next/navigation"
import Link from "next/link"
import { Button } from "@/components/ui/button"
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
import { Badge } from "@/components/ui/badge"
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar"
import { Textarea } from "@/components/ui/textarea"
import { Separator } from "@/components/ui/separator"
import {
  ArrowLeft, Heart, Share, Copy, Download, User, Calendar, Eye, Cpu, Monitor, MemoryStick, HardDrive, Zap, Fan, Box, Send, BatteryCharging, Server as MotherboardIcon, MoreHorizontal
} from "lucide-react"
import { supabase } from "@/lib/supabase"
import { formatCurrency } from "@/lib/currency"
import { useAuth } from "@/contexts/supabase-auth-context"
import { getUpgradeRecommendations } from "@/lib/algorithm-service"
import { swal } from "@/lib/sweetalert"
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu"
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog"
import { Input } from "@/components/ui/input"
import { TrendingUp, Loader2 } from "lucide-react"

const categoryMap = {
  1: "CPU",
  2: "Motherboard",
  3: "RAM",
  4: "Storage",
  5: "GPU",
  6: "PSU",
  7: "Case",
  8: "Cooling",
};

const categoryIcons = {
  CPU: Cpu,
  Motherboard: MotherboardIcon,
  RAM: MemoryStick,
  Storage: HardDrive,
  GPU: Monitor,
  PSU: BatteryCharging,
  Case: Box,
  Cooling: Fan,
}

export default function BuildDetailPage() {
  const params = useParams()
  const router = useRouter()
  const pathname = usePathname()
  const { user } = useAuth()

  const [build, setBuild] = useState<any>(null)
  const [creator, setCreator] = useState<any>(null)
  const [loading, setLoading] = useState(true)
  const [isLiked, setIsLiked] = useState(false)
  const [likeCount, setLikeCount] = useState(0);
  const [viewCount, setViewCount] = useState(0);
  const [comment, setComment] = useState("")
  const [totalUserBuilds, setTotalUserBuilds] = useState(0)
  const [comments, setComments] = useState<any[]>([]) // empty array initially
  const [isFollowing, setIsFollowing] = useState(false);
  const [isSubmittingComment, setIsSubmittingComment] = useState(false);
  const [followerCount, setFollowerCount] = useState(0);
  const [isTogglingFollow, setIsTogglingFollow] = useState(false);
  const [upgradeRecommendations, setUpgradeRecommendations] = useState<any[]>([])
  const [showUpgradeDialog, setShowUpgradeDialog] = useState(false)
  const [isLoadingUpgrades, setIsLoadingUpgrades] = useState(false)
  const [upgradeError, setUpgradeError] = useState<string | null>(null)
  const [likeOwnPopupOpen, setLikeOwnPopupOpen] = useState(false)
  const [sharePopupOpen, setSharePopupOpen] = useState(false)
  const [shareUrl, setShareUrl] = useState("")
  const [replyTo, setReplyTo] = useState<number | null>(null);
  const [likedCommentIds, setLikedCommentIds] = useState<number[]>([]);
  const [openReplyIds, setOpenReplyIds] = useState<number[]>([]);
  const [editingCommentId, setEditingCommentId] = useState<number | null>(null);
  const editInputRef = useRef<HTMLInputElement | null>(null);

  useEffect(() => {
    if (typeof window === "undefined") return;
    if (!comments || comments.length === 0) return;

    const hash = window.location.hash; // e.g., #comment-123
    if (!hash.startsWith("#comment-")) return;

    const commentId = hash.replace("#comment-", "");

    // Wait until the comment element exists
    const scrollToComment = () => {
      const element = document.getElementById(`comment-${commentId}`);
      if (element) {
        element.scrollIntoView({ behavior: "smooth", block: "center" });
        return true;
      }
      return false;
    };

    if (!scrollToComment()) {
      const interval = setInterval(() => {
        if (scrollToComment()) clearInterval(interval);
      }, 50);
      return () => clearInterval(interval);
    }
  }, [pathname, comments]);

  useEffect(() => {
    const fetchBuild = async () => {
      if (!params.id) return;

      const { data: buildData, error: buildError } = await supabase
        .from("builds")
        .select(`
          *,
          build_components(*, components(*))
        `)
        .eq("build_id", Number(params.id))
        .single();

      if (buildError || !buildData) {
        setBuild(null);
        setLoading(false);
        return;
      }

      // Get total likes from build_likes
      const { count: totalLikes, error: likesError } = await supabase
        .from("build_likes")
        .select("*", { count: "exact", head: true })
        .eq("build_id", buildData.build_id);

      if (!likesError) setLikeCount(totalLikes || 0);

      // Map build_components into components object
      const componentsObj = (buildData.build_components || []).reduce((acc: any, comp: any) => {
        if (!comp.components) return acc;

        const categoryName = categoryMap[comp.components.category_id];
        if (!categoryName) return acc;

        if (!acc[categoryName]) acc[categoryName] = [];

        acc[categoryName].push({
          ...comp.components,
          price: comp.components.component_price ?? 0,
        });

        return acc;
      }, {});

      setBuild({
        ...buildData,
        name: buildData.build_name,
        totalPrice: buildData.total_price ?? 0,
        components: componentsObj,
      });

      // Fetch creator
      const { data: userData, error: userError } = await supabase
        .from("users")
        .select("*")
        .eq("user_id", buildData.user_id)
        .single();

      if (!userError && userData) {
        setCreator(userData);

        const { count, error: countError } = await supabase
          .from("builds")
          .select("*", { count: "exact", head: true })
          .eq("user_id", userData.user_id);

        if (!countError) setTotalUserBuilds(count || 0);

        // Fetch followers AFTER setting creator
        if (userData.user_id) {
          fetchFollowerData(userData.user_id.toString());
        }
      }

      if (user && creator) {
        const { data: followData, error: followError } = await supabase
          .from("followers")
          .select("*")
          .eq("user_id", creator.user_id)
          .eq("follower_user_id", user.user_id)
          .single();

        setIsFollowing(!followError && !!followData);
      }

      // check if current user already liked
      if (user) {
        const { data: likedData, error: likedError } = await supabase
          .from("build_likes")
          .select("*")
          .eq("build_id", buildData.build_id)
          .eq("user_id", user.user_id)
          .single();

        setIsLiked(!likedError && !!likedData);
      }

      setLoading(false);
    };

    fetchBuild();
    fetchComments(); // fetch comments separately

    // Increase views (unique per user)
    const incrementViews = async () => {
      if (!params.id || !user) return;

      const buildId = Number(params.id);

      // Check if user already viewed this build
      const { data: existingView, error: viewError } = await supabase
        .from("build_views")
        .select("*")
        .eq("build_id", buildId)
        .eq("user_id", user.user_id)
        .single();

      if (existingView) return; // already viewed

      // Insert new view record (Supabase will auto-generate view_id and created_at)
      await supabase
        .from("build_views")
        .insert({
          build_id: buildId,
          user_id: user.user_id,
        });
    };

    incrementViews();

  }, [params.id, pathname, user]); // Refetch when params.id, pathname, or user changes

  useEffect(() => {
    const fetchBuildViews = async () => {
      if (!params.id) return;

      // Count all views for this build
      const { count: totalViews, error } = await supabase
        .from("build_views")
        .select("*", { count: "exact", head: true })
        .eq("build_id", Number(params.id));

      if (!error) setViewCount(totalViews || 0);
    };

    const incrementAndFetchViews = async () => {
      if (!params.id || !user) return;

      const buildId = Number(params.id);

      const { data: existingView } = await supabase
        .from("build_views")
        .select("*")
        .eq("build_id", buildId)
        .eq("user_id", user.user_id)
        .single();

      if (!existingView) {
        await supabase.from("build_views").insert({
          build_id: buildId,
          user_id: user.user_id,
        });
      }

      // Fetch the updated view count after increment
      await fetchBuildViews();
    };

    incrementAndFetchViews();
  }, [params.id, user]);

  useEffect(() => {
    if (editingCommentId !== null) {
      editInputRef.current?.focus();
    }
  }, [editingCommentId]);

  const fetchComments = async () => {
    if (!params.id) return;

    try {
      const { data: commentsData, error: commentsError } = await supabase
        .from("build_comments")
        .select(`
          *,
          users:user_id (
            user_name,
            avatar_url
          ),
          comment_likes(count)
        `)
        .eq("build_id", Number(params.id))
        .order("created_at", { ascending: false }); // latest first

      if (commentsError) {
        console.error("Error fetching comments:", commentsError);
        setComments([]);
        return;
      }

      if (commentsData) {
        const mappedComments = commentsData.map((c: any) => ({
          id: c.comment_id,
          user_id: c.user_id,
          user: c.users?.user_name || "Anonymous",
          avatar: c.users?.avatar_url ?? null,
          content: c.content,
          timestamp: new Date(c.created_at).toLocaleString("en-US", {
            year: "numeric",
            month: "short",
            day: "numeric",
            hour: "numeric",
            minute: "numeric",
            hour12: true
          }),
          likes: c.comment_likes?.[0]?.count || 0,
          reply_to: c.reply_to,
        }));

        setComments(mappedComments);

        // ✅ FETCH LIKED COMMENTS HERE
        if (user) {
          const commentIds = commentsData.map(c => c.comment_id);

          if (commentIds.length > 0) {
            const { data: likedData } = await supabase
              .from("comment_likes")
              .select("comment_id")
              .eq("user_id", user.user_id)
              .in("comment_id", commentIds);

            if (likedData) {
              setLikedCommentIds(likedData.map(l => l.comment_id));
            }
          }
        }
      } else {
        console.log(`ℹ️ No comments found for build ${params.id}`);
        setComments([]);
      }
    } catch (err) {
      console.error("Error in fetchComments:", err);
      setComments([]);
    }
  };

  const fetchFollowerData = async (creatorId: string) => {
    if (!creatorId) {
      const { count: followersCount, error: countError } = await supabase
        .from("followers")
        .select("*", { count: "exact", head: true })
        .eq("user_id", creatorId);

      if (!countError) setFollowerCount(followersCount || 0);
      setIsFollowing(false);
      return;
    }

    if (!user) {
      const { count: followersCount, error: countError } = await supabase
        .from("followers")
        .select("*", { count: "exact", head: true })
        .eq("user_id", creatorId);

      if (!countError) setFollowerCount(followersCount || 0);
      setIsFollowing(false);
      return;
    }

    try {
      const { count: followersCount, error: countError } = await supabase
        .from("followers")
        .select("*", { count: "exact", head: true })
        .eq("user_id", creatorId);

      if (!countError) setFollowerCount(followersCount || 0);

      const { data: followData, error: followError } = await supabase
        .from("followers")
        .select("*")
        .eq("user_id", creatorId)
        .eq("follower_user_id", user.user_id)
        .maybeSingle();

      setIsFollowing(!!followData);
    } catch (err) {
      console.error("Error in fetchFollowerData:", err);
    }
  };

  const handleAddComment = async () => {
    if (!comment.trim() || !user) return;
    setIsSubmittingComment(true);

    try {
      const { data: newComment, error } = await supabase
        .from("build_comments")
        .insert({
          build_id: build.build_id,
          user_id: user.user_id,
          content: comment.trim(),
          reply_to: replyTo, // <-- set reply_to if replying
        })
        .select()
        .single();

      if (!error && newComment) {
        setComments(prev => [
          {
            ...newComment,
            id: newComment.comment_id,
            user_id: user.user_id, // ✅ ADD THIS
            user: user.user_name,
            avatar: user.avatar_url,
            reply_to: replyTo,
            timestamp: new Date(newComment.created_at).toLocaleString("en-US", {
              year: "numeric",
              month: "short",
              day: "numeric",
              hour: "numeric",
              minute: "numeric",
              hour12: true
            }),
            likes: 0
          },
          ...prev
        ]);
        setComment("");
        setReplyTo(null);

        // Send push notification to the build owner (non-blocking)
        if (build.user_id !== user.user_id) {
          try {
            const payload = {
              userId: build.user_id,
              notificationType: 'comment',
              title: `${user.user_name} commented on your build`,
              body: `${user.user_name} replied: "${comment.trim().substring(0, 50)}${comment.trim().length > 50 ? '...' : ''}"`,
              url: `/builds/${build.build_id}`,
            };

            console.log('Sending push notification for comment:', payload);

            const res = await fetch('/api/notifications/send', {
              method: 'POST',
              headers: { 'Content-Type': 'application/json' },
              body: JSON.stringify(payload),
            });

            const sendResult = await res.json();
            console.log('Push send result for comment:', sendResult);
          } catch (err) {
            console.error('Error sending push notification after comment:', err);
          }
        }

        // If this is a reply, also notify the original comment author
        if (replyTo) {
          try {
            // Fetch the original comment to get the author's user_id
            const { data: originalComment, error: fetchError } = await supabase
              .from("build_comments")
              .select("user_id")
              .eq("comment_id", replyTo)
              .single();

            if (!fetchError && originalComment && originalComment.user_id !== user.user_id) {
              // Send notification to the person being replied to
              const payload = {
                userId: originalComment.user_id,
                notificationType: 'comment',
                title: `${user.user_name} replied to your comment`,
                body: `${user.user_name} replied: "${comment.trim().substring(0, 50)}${comment.trim().length > 50 ? '...' : ''}"`,
                url: `/builds/${build.build_id}`,
              };

              console.log('Sending push notification for comment reply:', payload);

              const res = await fetch('/api/notifications/send', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify(payload),
              });

              const sendResult = await res.json();
              console.log('Push send result for comment reply:', sendResult);
            }
          } catch (err) {
            console.error('Error sending push notification for reply:', err);
          }
        }
      }
    } catch (err) {
      console.error(err);
    } finally {
      setIsSubmittingComment(false);
    }
  };

  const handleDeleteComment = async (commentId: number) => {
    if (!user) return;

    try {
      const { error } = await supabase
        .from("build_comments")
        .delete()
        .eq("comment_id", commentId)
        .eq("user_id", user.user_id); // security: only delete own

      if (!error) {
        setComments(prev => prev.filter(c => c.id !== commentId));
      }
    } catch (err) {
      console.error(err);
    }
  };

  const handleUpdateComment = async (commentId: number, newContent: string) => {
    if (!user) return;

    const { error } = await supabase
      .from("build_comments")
      .update({ content: newContent })
      .eq("comment_id", commentId)
      .eq("user_id", user.user_id);

    if (!error) {
      setComments(prev =>
        prev.map(c =>
          c.id === commentId
            ? { ...c, content: newContent }
            : c
        )
      );

      setEditingCommentId(null);
    }
  };



  const toggleReplies = (commentId: number) => {
    setOpenReplyIds(prev =>
      prev.includes(commentId)
        ? prev.filter(id => id !== commentId) // close
        : [...prev, commentId] // open
    );
  };

  const handleLikeComment = async (commentId: number) => {
    if (!user) {
      swal.info("Login required", "Please log in to like comments.");
      return;
    }

    const alreadyLiked = likedCommentIds.includes(commentId);

    try {
      if (alreadyLiked) {
        // 🔥 UNLIKE
        await supabase
          .from("comment_likes")
          .delete()
          .eq("comment_id", commentId)
          .eq("user_id", user.user_id);

        await supabase
          .from("build_comments")
          .update({ likes: supabase.rpc ? undefined : undefined });

        setLikedCommentIds(prev => prev.filter(id => id !== commentId));

        setComments(prev =>
          prev.map(c =>
            c.id === commentId
              ? { ...c, likes: Math.max(0, c.likes - 1) }
              : c
          )
        );

      } else {
        // ❤️ LIKE
        await supabase
          .from("comment_likes")
          .insert({
            comment_id: commentId,
            user_id: user.user_id,
          });

        setLikedCommentIds(prev => [...prev, commentId]);

        setComments(prev =>
          prev.map(c =>
            c.id === commentId
              ? { ...c, likes: c.likes + 1 }
              : c
          )
        );

        // notification
        const { data: commentData } = await supabase
          .from("build_comments")
          .select("user_id")
          .eq("comment_id", commentId)
          .single();

        if (commentData?.user_id !== user.user_id) {
          await supabase.from("notifications").insert({
            user_id: commentData.user_id,
            actor_user_id: user.user_id,
            build_id: build.build_id,
            comment_id: commentId,
            type: "comment_like",
          });
        }
      }
    } catch (err) {
      console.error(err);
    }
  };

  const handleReply = (commentId: number, userName: string) => {
    if (!user) { swal.info("Login required", "Please log in to reply to comments."); return; }
    setReplyTo(commentId);
    setComment(`@${userName} `);
    const textarea = document.querySelector('textarea') as HTMLTextAreaElement;
    if (textarea) {
      textarea.focus();
      textarea.setSelectionRange(textarea.value.length, textarea.value.length);
    }
  };

  const CommentItem = ({ comment, comments, handleReply, handleLikeComment }: any) => {
    const replies = comments.filter(c => c.reply_to === comment.id);
    const profileHref =
      user && comment.user_id === user.user_id
        ? "/profile"
        : `/profile/${comment.user_id}`;
    const isCommentLiked = likedCommentIds.includes(comment.id);
    const [isEditing, setIsEditing] = useState(false);
    const [editedContent, setEditedContent] = useState(comment.content);
    const editInputRef = useRef<HTMLInputElement | null>(null);

    useEffect(() => {
      if (isEditing) editInputRef.current?.focus();
    }, [isEditing]);

    return (
      <div
        id={`comment-${comment.id}`}
        className="group flex gap-3 flex-col"
      >
        <div className="flex gap-3">
          <Link href={profileHref}>
            <Avatar className="h-8 w-8 cursor-pointer hover:ring-2 hover:ring-blue-500 transition">
              {comment.avatar && comment.avatar !== "/placeholder.svg" ? (
                <AvatarImage src={comment.avatar} />
              ) : (
                <AvatarFallback>
                  {comment.user?.charAt(0).toUpperCase() || "?"}
                </AvatarFallback>
              )}
            </Avatar>
          </Link>
          <div className="flex-1">
            <div className="flex items-center justify-between mb-1">
              <div className="flex items-center gap-2">
                <span className="font-medium text-sm">{comment.user}</span>
                <span className="text-xs text-slate-500">{comment.timestamp}</span>
              </div>

              {user && comment.user_id === user.user_id && (
                <DropdownMenu>
                  <DropdownMenuTrigger asChild>
                    <Button
                      variant="ghost"
                      size="icon"
                      className="h-6 w-6 opacity-0 group-hover:opacity-100 transition"
                    >
                      <MoreHorizontal className="h-4 w-4" />
                    </Button>
                  </DropdownMenuTrigger>

                  <DropdownMenuContent align="end">
                    <DropdownMenuItem
                      onClick={() => {
                        setEditingCommentId(comment.id);
                        setEditedContent(comment.content);
                      }}
                    >
                      Edit
                    </DropdownMenuItem>

                    <DropdownMenuItem
                      onClick={() => handleDeleteComment(comment.id)}
                      className="text-red-500"
                    >
                      Delete
                    </DropdownMenuItem>
                  </DropdownMenuContent>
                </DropdownMenu>
              )}
            </div>
            {editingCommentId === comment.id ? (
              <div className="flex gap-2 mt-1">
                <Input
                  ref={editInputRef}
                  value={editedContent}
                  onChange={(e) => setEditedContent(e.target.value)}
                  className="h-8 text-sm"
                />
                <Button
                  size="sm"
                  onClick={() => handleUpdateComment(comment.id, editedContent)} // ✅ use local state
                >
                  Save
                </Button>
                <Button
                  size="sm"
                  variant="ghost"
                  onClick={() => setEditingCommentId(null)}
                >
                  Cancel
                </Button>
              </div>
            ) : (
              <p className="text-sm text-slate-700">{comment.content}</p>
            )}
            <div className="flex items-center gap-4 text-xs">
              <Button
                variant="ghost"
                size="sm"
                className={`h-auto p-0 flex items-center gap-1 text-xs transition-colors ${
                  isCommentLiked
                    ? "text-red-500 hover:text-red-600"
                    : "text-slate-500 hover:text-red-500"
                }`}
                onClick={() => handleLikeComment(comment.id)}
              >
                <Heart className={`h-3 w-3 ${isCommentLiked ? "fill-current" : ""}`} />
                <span>{comment.likes}</span>
              </Button>
              <Button
                variant="ghost"
                size="sm"
                className="h-auto p-0 text-slate-500 hover:text-slate-700"
                onClick={() => handleReply(comment.id, comment.user)}
              >
                Reply
              </Button>
            </div>
          </div>
        </div>

        {/* Toggle replies button */}
        {replies.length > 0 && (
          <div className="ml-10 mt-1">
            <Button
              variant="link"
              size="sm"
              className="text-xs p-0 text-slate-500 hover:underline"
              onClick={() => toggleReplies(comment.id)}
            >
              {openReplyIds.includes(comment.id)
                ? `Hide Replies (${replies.length})`
                : `Show Replies (${replies.length})`}
            </Button>
          </div>
        )}


        {/* Nested replies */}
        {openReplyIds.includes(comment.id) && replies.length > 0 && (
          <div className="ml-10 mt-2 space-y-2">
            {replies.map(reply => (
              <CommentItem
                key={`${comment.id}-${reply.id}`}
                comment={reply}
                comments={comments}
                handleReply={handleReply}
                handleLikeComment={handleLikeComment}
              />
            ))}
          </div>
        )}
      </div>
    );
  };


  const formatDate = (isoDate: string) => {
    const date = new Date(isoDate);
    return date.toLocaleDateString("en-US", {
      year: "numeric",
      month: "short",
      day: "numeric",
    });
  };

  const toggleLike = async () => {
    if (!user) return;

    // ❌ Prevent liking your own build
    if (creator?.user_id === user.user_id) {
      setLikeOwnPopupOpen(true)
      return
    }

    if (isLiked) {
      const { error: deleteLikeError } = await supabase
        .from("build_likes")
        .delete()
        .eq("build_id", build.build_id)
        .eq("user_id", user.user_id);

      if (!deleteLikeError) {
        setIsLiked(false);
        setLikeCount((prev) => Math.max(0, prev - 1));
        await supabase
          .from("notifications")
          .delete()
          .eq("type", "like")
          .eq("user_id", creator.user_id)
          .eq("actor_user_id", user.user_id)
          .eq("build_id", build.build_id);
      }
    } else {
      const { error: insertLikeError } = await supabase
        .from("build_likes")
        .insert({ build_id: build.build_id, user_id: user.user_id });

      if (!insertLikeError) {
        setIsLiked(true);
        setLikeCount((prev) => prev + 1);
        await supabase.from("notifications").insert({
          user_id: creator.user_id,
          actor_user_id: user.user_id,
          build_id: build.build_id,
          type: "like",
        });
        // Send push notification to the build owner (non-blocking)
        try {
          const payload = {
            userId: creator.user_id,
            notificationType: 'buildLike',
            title: `${user.user_name} liked your build`,
            body: `${user.user_name} liked ${build.build_name}`,
            url: `/builds/${build.build_id}`,
          };

          console.log('Sending push notification payload (build detail):', payload);

          fetch('/api/notifications/send', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify(payload),
          })
            .then(res => res.json().then(r => console.log('Push send result (build detail):', r)).catch(() => {}))
            .catch(err => console.error('Error sending push (build detail):', err));
        } catch (err) {
          console.error('Error preparing push send (build detail):', err);
        }
      }
    }
  };

  const toggleFollow = async () => {
    if (!user) { swal.info("Login required", "Please log in to follow users."); return; }
    if (!creator) { swal.error("Error", "Creator information not available."); return; }
    if (user.user_id === creator.user_id) { swal.warning("Cannot follow", "You cannot follow yourself."); return; }

    setIsTogglingFollow(true);
    try {
      if (isFollowing) {
        const { error: deleteError } = await supabase
          .from("followers")
          .delete()
          .eq("user_id", creator.user_id)
          .eq("follower_user_id", user.user_id);

        if (deleteError) { console.error("Error unfollowing:", deleteError); swal.error("Unfollow failed", "Please try again."); return; }

        setIsFollowing(false);
        setFollowerCount((prev) => Math.max(0, prev - 1));
        // Optionally: delete the follow notification if you want
        await supabase.from("notifications")
          .delete()
          .eq("type", "follow")
          .eq("user_id", creator.user_id)
          .eq("actor_user_id", user.user_id);
        } else {
          // Follow: Insert the follow relationship
          const { error: insertError } = await supabase
            .from("followers")
            .insert({
              user_id: creator.user_id,
              follower_user_id: user.user_id,
            });

          if (insertError) {
            console.error("Error following:", insertError);
            if (insertError.code === "23505") {
              swal.info("Already following", "You are already following this user.");
              setIsFollowing(true);
            } else {
              swal.error("Follow failed", "Please try again.");
            }
            return;
          }

          console.log("✅ Successfully followed user");
          setIsFollowing(true);
          setFollowerCount((prev) => prev + 1);

          // 🟢 Insert notification for the follow
          const { error: notifError } = await supabase
            .from("notifications")
            .insert({
              user_id: creator.user_id, // recipient of the notification
              actor_user_id: user.user_id, // the follower
              type: "follow",
            });

          if (notifError) {
            console.error("Error creating follow notification:", notifError);
          } else {
            console.log("✅ Follow notification created");

            // Send push notification to the followed user (non-blocking)
            try {
              const payload = {
                userId: creator.user_id,
                notificationType: 'followers',
                title: `${user.user_name} started following you`,
                body: `${user.user_name} is now following you`,
                url: `/profile/${user.user_id}`,
              };

              console.log('Sending push notification for new follower:', payload);

              const res = await fetch('/api/notifications/send', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify(payload),
              });

              const sendResult = await res.json();
              console.log('Push send result for follower:', sendResult);
            } catch (err) {
              console.error('Error sending push notification for follower:', err);
            }
          }
        }

        // Refresh follow status and count to ensure consistency
        await fetchFollowerData(creator.user_id);

        } catch (err) {
          console.error("Error in toggleFollow:", err);
          swal.error("Error", "An error occurred. Please try again.");
        } finally {
          setIsTogglingFollow(false);
        }
        };

        const handleGetUpgradeRecommendations = async () => {
          if (!build || !build.components) {
            setUpgradeError("Build data not available")
            setTimeout(() => setUpgradeError(null), 5000)
            return
          }

          setIsLoadingUpgrades(true)
          setUpgradeError(null)
          setUpgradeRecommendations([])

          try {
            // Convert build components to upgrade API format
            const currentBuild: any[] = []
            Object.entries(build.components).forEach(([categoryName, components]: [string, any]) => {
              if (Array.isArray(components) && components.length > 0) {
                const comp = components[0] // Take first component of each category
                const componentId = Number(String(comp.component_id).replace(/\D/g, '')) || 0
                currentBuild.push({
                  component_id: componentId,
                  component_name: comp.component_name || comp.name || 'Unknown',
                  component_price: comp.component_price || comp.price || 0,
                  category_name: categoryName,
                })
              }
            })

            if (currentBuild.length === 0) {
              setUpgradeError("No components found in this build")
              setTimeout(() => setUpgradeError(null), 5000)
              return
            }

            console.log("Requesting upgrade recommendations for build:", currentBuild)
            const recommendations = await getUpgradeRecommendations(currentBuild)
            console.log("Received upgrade recommendations:", recommendations)

            if (!recommendations || recommendations.length === 0) {
              setUpgradeError("No upgrade recommendations available for this build")
              setTimeout(() => setUpgradeError(null), 5000)
              return
            }

            setUpgradeRecommendations(recommendations)
            setShowUpgradeDialog(true)
          } catch (error: any) {
            console.error("Error getting upgrade recommendations:", error)
            setUpgradeError(error.message || "Failed to get upgrade recommendations")
            setTimeout(() => setUpgradeError(null), 5000)
          } finally {
            setIsLoadingUpgrades(false)
          }
        };

        if (loading) {
          return (
            <div className="min-h-screen bg-gradient-to-br from-slate-50 to-slate-100 dark:from-slate-900 dark:to-slate-800">
              <div className="container mx-auto px-4 py-20 text-center">
                <Cpu className="h-12 w-12 text-blue-600 mx-auto mb-4 animate-pulse" />
                <p className="text-slate-600 dark:text-slate-400">Loading builds...</p>
              </div>
            </div>
          )
        }

        if (!build) {
          return (
            <div className="min-h-screen flex items-center justify-center">
              <div className="text-center">
                <h2 className="text-2xl font-bold mb-2">Build not found</h2>
                <Button asChild>
                  <Link href="/builds">Back to Builds</Link>
                </Button>
              </div>
            </div>
          )
        }

        const totalComponents = Object.values(build.components || {}).flat().length;
        const profileHref =
          user && creator.user_id === user.user_id
            ? "/profile"
            : `/profile/${creator.user_id}`;
  return (
    <div className="min-h-screen bg-gradient-to-br from-slate-50 to-slate-100 dark:from-slate-900 dark:to-slate-800">
      <div className="container mx-auto px-4 py-8">
        <div className="grid lg:grid-cols-3 gap-8">
          {/* Main Content */}
          <div className="lg:col-span-2 space-y-6">
            {/* Build Header */}
            <Card>
              <CardHeader>
                <div className="flex items-start justify-between">
                  <div>
                    <CardTitle className="text-2xl mb-2">{build.name}</CardTitle>
                    <div className="flex items-center gap-3 mb-3">
                      <Link href={profileHref}>
                        <Avatar className="h-8 w-8 cursor-pointer hover:ring-2 hover:ring-blue-500 transition">
                          {creator?.avatar_url ? (
                            <AvatarImage src={creator?.avatar_url} />
                          ) : (
                            <AvatarFallback className="text-xs">
                              {creator?.user_name ? creator?.user_name?.charAt(0).toUpperCase() : "?"}
                            </AvatarFallback>
                          )}
                        </Avatar>
                      </Link>
                      <div>
                        <p className="font-medium text-slate-900 dark:text-white">{creator?.user_name || "Unknown"}</p>
                        <div className="flex items-center gap-4 text-sm text-slate-500">
                          <div className="flex items-center gap-1">
                            <Calendar className="h-3 w-3" />
                            <span>{formatDate(creator?.created_at)}</span>
                          </div>
                          <div className="flex items-center gap-1">
                            <Eye className="h-3 w-3" />
                            <span>{viewCount} views</span>
                          </div>
                        </div>
                      </div>
                    </div>
                    <p className="text-slate-600 dark:text-slate-400">{build.description}</p>
                  </div>
                  <Badge variant="secondary" className="text-lg font-bold px-3 py-1">
                    {formatCurrency(build.totalPrice)}
                  </Badge>
                </div>
                {/* Tags */}
                <div className="flex flex-wrap gap-2">
                  {(build.tags || []).map((tag: string) => (
                    <Badge key={tag} variant="outline">{tag}</Badge>
                  ))}
                </div>
                {/* Upgrade Suggestions Button */}
                <div className="pt-4 border-t border-slate-200 dark:border-slate-700">
                  <Button onClick={handleGetUpgradeRecommendations} disabled={isLoadingUpgrades} variant="default" className="gap-2 w-full sm:w-auto">
                    {isLoadingUpgrades ? (
                      <>
                        <Loader2 className="h-4 w-4 animate-spin" /> Loading...
                      </>
                    ) : (
                      <>
                        <TrendingUp className="h-4 w-4" /> Get Upgrade Suggestions
                      </>
                    )}
                  </Button>
                  {upgradeError && (
                    <p className="text-sm text-red-600 mt-2">{upgradeError}</p>
                  )}
                </div>
                {/* Actions */}
                <div className="flex items-center gap-4 pt-4">
                  <Button variant={isLiked ? "default" : "outline"} onClick={toggleLike} className="flex items-center gap-2">
                    <Heart className={`h-4 w-4 ${isLiked ? "fill-current text-red-500" : ""}`} /> {likeCount} Likes
                  </Button>
                  <Button variant="outline" className="flex items-center gap-2 bg-transparent" onClick={() => {
                    if (typeof window !== "undefined") {
                      const builderUrl = new URL(`${window.location.origin}/builder`);
                      builderUrl.searchParams.set("clone", build.build_id);
                      window.location.href = builderUrl.toString();
                    }
                  }}>
                    <Copy className="h-4 w-4" /> Clone Build
                  </Button>
                 <Button
                    variant="outline"
                    className="flex items-center gap-2"
                    onClick={() => {
                      if (typeof window !== "undefined") {
                        const url = `${window.location.origin}/builder?share=${build.build_id}`
                        setShareUrl(url)
                        setSharePopupOpen(true)
                      }
                    }}
                  >
                    <Share className="h-4 w-4" /> Share
                  </Button>

                </div>
              </CardHeader>
            </Card>

            {/* Components List */}
            <Card>
              <CardHeader>
                <CardTitle>Components ({totalComponents}/8)</CardTitle>
                <CardDescription>Complete parts list for this build</CardDescription>
              </CardHeader>
              <CardContent className="space-y-4">
                {Object.entries(build.components || {}).map(([category, comps]) => {
                  const Icon = categoryIcons[category] || Box;
                  return comps.map((component, idx) => (
                    <div key={`${category}-${idx}`} className="flex items-center gap-4 p-4 border border-slate-200 dark:border-slate-700 rounded-lg">
                      {component.image && component.image !== '/placeholder.svg' ? (
                        <img src={component.image} alt={component.component_name || component.name || 'Component'} className="w-16 h-16 object-cover rounded-lg bg-slate-100 dark:bg-slate-800 flex-shrink-0" onError={(e) => { (e.target as HTMLImageElement).src = '/placeholder.svg' }} />
                      ) : (
                        <Icon className="h-8 w-8 text-slate-500 flex-shrink-0" />
                      )}
                      <div className="flex-1">
                        <h3 className="font-medium text-slate-900 dark:text-white capitalize">
                          {category === "psu" ? "Power Supply" : category}
                        </h3>
                        <p className="text-sm text-slate-600 dark:text-slate-400">
                          {component.component_brand ? `${component.component_brand} ` : ''}{component.component_name || component.name || 'Unknown Component'}
                        </p>
                        {(component.rating || component.reviews) && (
                          <div className="flex items-center gap-4 mt-1 text-xs text-slate-500">
                            {component.rating && <span>★ {component.rating}</span>}
                            {component.reviews && <span>{component.reviews} reviews</span>}
                          </div>
                        )}
                      </div>
                      <div className="text-right">
                        <p className="font-semibold text-slate-900 dark:text-white">{formatCurrency(component.price || component.component_price || 0)}</p>
                      </div>
                    </div>
                  ));
                })}
              </CardContent>
            </Card>

            {/* Comments Section */}
            <Card>
              <CardHeader>
                <CardTitle>Comments ({comments.length})</CardTitle>
              </CardHeader>
              <CardContent className="space-y-6">
                {/* Add Comment */}
                {user && (
                  <div className="space-y-3">
                    <Textarea placeholder="Share your thoughts about this build..." value={comment} onChange={(e) => setComment(e.target.value)} className="min-h-20" />
                    <div className="flex justify-end">
                      <Button onClick={handleAddComment} disabled={!comment.trim() || isSubmittingComment}>
                        <Send className="h-4 w-4 mr-2" /> {isSubmittingComment ? "Posting..." : "Post Comment"}
                      </Button>
                    </div>
                  </div>
                )}
                <Separator />
                {/* Comments List */}
                <div className="space-y-4">
                  {comments.length === 0 ? (
                    <div className="text-center py-8 text-slate-500 dark:text-slate-400">
                      No comments yet. Be the first to comment!
                    </div>
                  ) : (
                    <>
                      {/* Render only top-level comments (reply_to === null) */}
                      {comments
                        .filter(c => !c.reply_to)
                        .map(comment => (
                          <CommentItem
                            key={comment.id}
                            comment={comment}
                            comments={comments}
                            handleReply={handleReply}
                            handleLikeComment={handleLikeComment}
                          />
                        ))}
                    </>
                  )}
                </div>
              </CardContent>
            </Card>
          </div>

          {/* Sidebar */}
          <div className="space-y-6">
            {/* Build Stats */}
            <Card>
              <CardHeader>
                <CardTitle>Build Statistics</CardTitle>
              </CardHeader>
              <CardContent className="space-y-3">
                <div className="flex justify-between text-sm">
                  <span className="text-slate-600 dark:text-slate-400">Total Components</span>
                  <span className="font-medium">{totalComponents}/8</span>
                </div>
                <div className="flex justify-between text-sm">
                  <span className="text-slate-600 dark:text-slate-400">Total Price</span>
                  <span className="font-medium">{formatCurrency(build.totalPrice)}</span>
                </div>
                <div className="flex justify-between text-sm">
                  <span className="text-slate-600 dark:text-slate-400">Likes</span>
                  <span className="font-medium">{likeCount}</span>
                </div>
                <div className="flex justify-between text-sm">
                  <span className="text-slate-600 dark:text-slate-400">Views</span>
                  <span className="font-medium">{viewCount}</span>
                </div>
                <div className="flex justify-between text-sm">
                  <span className="text-slate-600 dark:text-slate-400">Comments</span>
                  <span className="font-medium">{comments.length}</span>
                </div>
              </CardContent>
            </Card>

            {/* Creator Info */}
            <Card>
              <CardHeader>
                <CardTitle>About the Creator</CardTitle>
              </CardHeader>
              <CardContent>
                <div className="flex items-center gap-3 mb-4">
                  <Link href={profileHref}>
                    <Avatar className="h-12 w-12 cursor-pointer hover:ring-2 hover:ring-blue-500 transition">
                      {creator?.avatar_url ? (
                        <AvatarImage src={creator?.avatar_url} />
                      ) : (
                        <AvatarFallback>
                            {creator?.user_name ? creator?.user_name?.charAt(0).toUpperCase() : "?"}
                      </AvatarFallback>
                      )}
                    </Avatar>
                  </Link>
                  <div>
                    <h3 className="font-medium">{creator?.user_name || "Unknown"}</h3>
                    <p className="text-sm text-slate-500">{formatDate(creator?.created_at)}</p>
                  </div>
                </div>
                <div className="grid grid-cols-2 gap-4 text-sm">
                  <div>
                    <span className="text-slate-600 dark:text-slate-400">Builds</span>
                    <p className="font-medium">{totalUserBuilds}</p>
                  </div>
                  <div>
                    <span className="text-slate-600 dark:text-slate-400">Followers</span>
                    <p className="font-medium">{followerCount}</p>
                  </div>
                </div>
                {/* Follow Button – hide if viewing own profile */}
                {user && creator && user.user_id !== creator.user_id && (
                  <Button
                    className="w-full mt-4"
                    variant={isFollowing ? "default" : "outline"}
                    onClick={toggleFollow}
                    disabled={isTogglingFollow}
                  >
                    <User className="h-4 w-4 mr-2" />
                    {isTogglingFollow
                      ? (isFollowing ? "Unfollowing..." : "Following...")
                      : (isFollowing ? "Following" : "Follow")}
                  </Button>
                )}
              </CardContent>
            </Card>
          </div>
        </div>
      </div>

      {/* Upgrade Recommendations Dialog */}
      <Dialog open={showUpgradeDialog} onOpenChange={setShowUpgradeDialog}>
        <DialogContent className="max-w-4xl max-h-[80vh] overflow-y-auto">
          <DialogHeader>
            <DialogTitle className="flex items-center gap-2">
              <TrendingUp className="h-5 w-5 text-green-600" /> Upgrade Recommendations
            </DialogTitle>
            <DialogDescription>Suggested component upgrades for this build. Import this build to apply upgrades.</DialogDescription>
          </DialogHeader>
          {upgradeRecommendations.length === 0 ? (
            <div className="text-center py-8">
              <p className="text-slate-600 dark:text-slate-400">No upgrade recommendations available.</p>
            </div>
          ) : (
            <div className="space-y-4">
              {upgradeRecommendations.map((rec, index) => (
                <Card key={index} className={`border-slate-200 dark:border-slate-700 ${rec.recommended_upgrade ? 'hover:border-green-500 hover:shadow-md transition-all' : 'opacity-75'}`}>
                  <CardContent className="p-4">
                    <div className="flex items-start justify-between gap-4">
                      <div className="flex-1 min-w-0">
                        <div className="flex items-center gap-2 mb-2">
                          <p className="text-sm font-semibold text-slate-900 dark:text-white">{rec.current_component}</p>
                        </div>
                        {rec.recommended_upgrade ? (
                          <div className="space-y-2">
                            <div className="flex items-center gap-2">
                              <span className="text-sm text-slate-500">→</span>
                              <p className="text-sm font-medium text-green-600 dark:text-green-400">{rec.recommended_upgrade}</p>
                            </div>
                            <div className="flex flex-col gap-1 ml-4">
                              {rec.new_price && (
                                <div className="flex items-center gap-2">
                                  <span className="text-xs text-slate-500">New price:</span>
                                  <span className="text-xs font-semibold text-slate-700 dark:text-slate-300">{formatCurrency(rec.new_price)}</span>
                                </div>
                              )}
                              {rec.upgrade_cost && (
                                <div className="flex items-center gap-2">
                                  <span className="text-xs text-slate-500">Upgrade cost:</span>
                                  <span className="text-xs font-semibold text-blue-600 dark:text-blue-400">{formatCurrency(rec.upgrade_cost)}</span>
                                </div>
                              )}
                            </div>
                          </div>
                        ) : (
                          <p className="text-xs text-slate-500 italic">No upgrade available for this component</p>
                        )}
                      </div>
                    </div>
                  </CardContent>
                </Card>
              ))}
              <div className="pt-4 border-t">
                <p className="text-sm text-slate-600 dark:text-slate-400 text-center">💡 Tip: Import this build to your builder to apply these upgrades</p>
              </div>
            </div>
          )}
        </DialogContent>
      </Dialog>
      {/* Popup for trying to like own build */}
      {likeOwnPopupOpen && (
        <div className="fixed inset-0 flex items-center justify-center z-50 bg-black/50">
          <div className="bg-white dark:bg-slate-900 rounded-lg shadow-lg p-6 w-80 max-w-sm text-center">
            <h3 className="text-lg font-semibold text-slate-900 dark:text-white mb-2">Oops!</h3>
              <p className="text-sm text-slate-600 dark:text-slate-400 mb-4">
                You cannot like your own build.
              </p>
              <button
                className="px-4 py-2 bg-blue-600 text-white rounded hover:bg-blue-700 transition"
                onClick={() => setLikeOwnPopupOpen(false)}
              >
                OK
              </button>
            </div>
          </div>
        )}
        {/* Share Popup */}
        {sharePopupOpen && (
          <div className="fixed inset-0 flex items-center justify-center z-50 bg-black/50">
            <div className="bg-white dark:bg-slate-900 rounded-lg shadow-lg p-6 w-80 max-w-sm text-center">
              <h3 className="text-lg font-semibold text-slate-900 dark:text-white mb-2">Share Build</h3>
              <p className="text-sm text-slate-600 dark:text-slate-400 mb-4">
                Copy the link below to share this build with others.
              </p>
              <div className="flex items-center gap-2 mb-4">
                <Input value={shareUrl} readOnly className="flex-1 text-sm" />
                <Button
                  size="sm"
                  onClick={async () => {
                    try {
                      await navigator.clipboard.writeText(shareUrl)
                      swal.success("Link copied!", "Link copied to clipboard.")
                    } catch (err) {
                      console.error(err)
                      swal.error("Failed to copy link", "Please copy manually: " + shareUrl)
                    }
                  }}
                >
                  Copy
                </Button>
              </div>
              <button
                className="px-4 py-2 bg-blue-600 text-white rounded hover:bg-blue-700 transition"
                onClick={() => setSharePopupOpen(false)}
              >
                Close
              </button>
            </div>
          </div>
        )}
    </div>
  )
}
