"use client"

import { useState, useEffect } from "react"
import Link from "next/link"
import { usePathname } from "next/navigation"
import { Button } from "@/components/ui/button"
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"
import { Badge } from "@/components/ui/badge"
import { Input } from "@/components/ui/input"
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar"
import { Cpu, Heart, MessageCircle, Share, Search, Monitor, Users, Eye, BarChart3, ArrowLeft, Plus, X, TrendingUp, TrendingDown, DollarSign, Zap, MemoryStick, HardDrive, Fan, Settings, Calendar } from "lucide-react"
import { buildService, buildComponentService } from "@/lib/database"
import { formatCurrency, PRICE_RANGES } from "@/lib/currency"
import { useAuth } from "@/contexts/supabase-auth-context"
import { supabase } from "@/lib/supabase"
import { swal } from "@/lib/sweetalert"

interface BuildWithDetails {
  build_id: number
  build_name: string
  date_created: string
  user_id: number
  build_type_id: number
  users: {
    user_id: number
    user_name: string
    email: string
    avatar_url: string
  }
  build_types: {
    build_type_id: number
    type_name: string
  }
  components?: any[]
  totalPrice?: number
  comments?: number
  views?: number
  description?: string
}

export default function BuildsPage() {
  const { user } = useAuth()
  const pathname = usePathname()
  const [builds, setBuilds] = useState<BuildWithDetails[]>([])
  const [statistics, setStatistics] = useState({ totalBuilders: 0, totalBuilds: 0, totalLikes: 0 })
  const [searchTerm, setSearchTerm] = useState("")
  const [sortBy, setSortBy] = useState("popular")
  const [priceFilter, setPriceFilter] = useState("all")
  const [typeFilter, setTypeFilter] = useState("all")
  const [buildsLimit, setBuildsLimit] = useState(30)
  const [likedBuilds, setLikedBuilds] = useState<number[]>([])
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState<string | null>(null)
  const [activeTab, setActiveTab] = useState<"browse" | "compare">("browse")
  const [selectedBuildsForCompare, setSelectedBuildsForCompare] = useState<BuildWithDetails[]>([])
  const [compareSearchTerm, setCompareSearchTerm] = useState("")
  const [compareActiveTab, setCompareActiveTab] = useState("overview")
  const [sharePopupOpen, setSharePopupOpen] = useState(false)
  const [shareUrl, setShareUrl] = useState("")

  // Subscriptions: set up once per pathname so "Load more" (buildsLimit) doesn't tear them down
  useEffect(() => {
    const buildsChannel = supabase
      .channel("builds-changes")
      .on("postgres_changes", { event: "*", schema: "public", table: "builds" }, () => {
        fetchBuilds()
        fetchStatistics()
      })
      .subscribe()

    const likesChannel = supabase
      .channel("likes-changes")
      .on("postgres_changes", { event: "*", schema: "public", table: "build_likes" }, () => {
        fetchBuilds()
        fetchStatistics()
      })
      .subscribe()

    return () => {
      supabase.removeChannel(buildsChannel)
      supabase.removeChannel(likesChannel)
    }
  }, [pathname])

  // Initial fetch and refetch when limit changes (Load more)
  useEffect(() => {
    fetchBuilds()
    fetchStatistics()
  }, [pathname, buildsLimit])


  // Fetch user's liked builds
  useEffect(() => {
    if (!user) return;
    const fetchLiked = async () => {
      const { data, error } = await supabase
        .from("build_likes")
        .select("build_id")
        .eq("user_id", user.user_id)
      if (!error && data) setLikedBuilds(data.map((r) => r.build_id))
    }
    fetchLiked()
  }, [user])

  const fetchBuilds = async () => {
    setLoading(true)

    try {
      // 1️⃣ Fetch builds with user info and components
      const { data: buildsData, error: buildsError } = await supabase
        .from("builds")
        .select(`
          *,
          users(user_name, user_id, avatar_url),
          build_types(build_type_id, type_name),
          build_components(
            components(
              component_name,
              component_categories(category_name)
            )
          )
        `)
        .order("date_created", { ascending: false })
        .limit(buildsLimit)

      if (buildsError) throw buildsError
      if (!buildsData || buildsData.length === 0) {
        setBuilds([])
        setLoading(false)
        return
      }

      const buildIds = buildsData.map(b => b.build_id)

      // 2️⃣ Fetch likes
      const { data: likesData } = await supabase
        .from("build_likes")
        .select("build_id")
        .in("build_id", buildIds)

      // 3️⃣ Fetch comments count
      const { data: commentsData } = await supabase
        .from("build_comments")
        .select("build_id")
        .in("build_id", buildIds)

      // 4️⃣ Fetch views count from build_views table
      const { data: viewsData } = await supabase
        .from("build_views")
        .select("build_id")
        .in("build_id", buildIds)

      // 5️⃣ Reduce counts
      const likeCountMap: Record<number, number> = {}
      likesData?.forEach(like => {
        likeCountMap[like.build_id] = (likeCountMap[like.build_id] || 0) + 1
      })

      const commentCountMap: Record<number, number> = {}
      commentsData?.forEach(comment => {
        commentCountMap[comment.build_id] = (commentCountMap[comment.build_id] || 0) + 1
      })

      const viewsCountMap: Record<number, number> = {}
      viewsData?.forEach(view => {
        viewsCountMap[view.build_id] = (viewsCountMap[view.build_id] || 0) + 1
      })

      // 6️⃣ Merge counts into builds
      const enrichedBuilds = buildsData.map(build => ({
        ...build,
        totalPrice: build.total_price,
        likes: likeCountMap[build.build_id] || 0,
        comments: commentCountMap[build.build_id] || 0,
        views: viewsCountMap[build.build_id] || 0,
        components: build.build_components?.map(bc => ({
          ...bc.components, // flatten components
          category_name: bc.components?.component_categories?.category_name
        })) || []
      }))


      setBuilds(enrichedBuilds)
    } catch (err: any) {
      console.error(err.message || "Unknown error")
      setError("Failed to fetch builds. Please try again.")
    } finally {
      setLoading(false)
    }
  }

  const fetchStatistics = async () => {
    try { const stats = await buildService.getStatistics(); setStatistics(stats) }
    catch (err) { console.error(err) }
  }

  const toggleLike = async (buildId: number) => {
    if (!user?.user_id) return

    const build = builds.find(b => b.build_id === buildId)
    const buildOwnerId = build?.user_id

    if (buildOwnerId === user.user_id) {
      swal.info("Oops!", "You cannot like your own build.")
      return
    }

    const alreadyLiked = likedBuilds.includes(buildId)

    if (alreadyLiked) {
      // UNLIKE
      await supabase
        .from("build_likes")
        .delete()
        .eq("build_id", buildId)
        .eq("user_id", user.user_id)

      setLikedBuilds(prev => prev.filter(id => id !== buildId))

      setBuilds(prev =>
        prev.map(b =>
          b.build_id === buildId
            ? { ...b, likes: Math.max(b.likes - 1, 0) }
            : b
        )
      )

      // Remove notification
      if (buildOwnerId && buildOwnerId !== user.user_id) {
        await supabase
          .from("notifications")
          .delete()
          .eq("user_id", buildOwnerId)
          .eq("actor_user_id", user.user_id)
          .eq("type", "like")
          .eq("build_id", buildId)
      }
    } else {
      // LIKE
      await supabase
        .from("build_likes")
        .insert({
          build_id: buildId,
          user_id: user.user_id,
          created_at: new Date().toISOString()
        })

      setLikedBuilds(prev => [...prev, buildId])

      setBuilds(prev =>
        prev.map(b =>
          b.build_id === buildId
            ? { ...b, likes: (b.likes || 0) + 1 }
            : b
        )
      )

      // Insert notification
      if (buildOwnerId && buildOwnerId !== user.user_id) {
        await supabase
          .from("notifications")
          .insert({
            user_id: buildOwnerId,
            actor_user_id: user.user_id,
            type: "like",
            build_id: buildId,
            created_at: new Date().toISOString(),
          })

        // Send push notification to the build owner (non-blocking)
        try {
          const payload = {
            userId: buildOwnerId,
            notificationType: 'buildLike',
            title: `${user.user_name} liked your build`,
            body: `${user.user_name} liked ${build.build_name}`,
            url: `/builds/${buildId}`,
          };

          console.log('Sending push notification payload (builds list):', 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 (builds list):', r)).catch(() => {}))
            .catch(err => console.error('Error sending push (builds list):', err));
        } catch (err) {
          console.error('Error preparing push send (builds list):', err);
        }
      }
    }
  }






  const getFilteredBuilds = (): BuildWithDetails[] => {
    let filtered = builds.filter(
      b =>
        b.build_name.toLowerCase().includes(searchTerm.toLowerCase()) ||
        b.build_types?.type_name?.toLowerCase().includes(searchTerm.toLowerCase()) ||
        (b.users?.user_name && b.users.user_name.toLowerCase().includes(searchTerm.toLowerCase()))
    )
    if (priceFilter !== "all") {
      filtered = filtered.filter(build => {
        const price = build.totalPrice || 0
        switch (priceFilter) {
          case "budget": return price < PRICE_RANGES.budget.max
          case "mid": return price >= PRICE_RANGES.mid.min && price < PRICE_RANGES.mid.max
          case "high": return price >= PRICE_RANGES.high.min
          default: return true
        }
      })
    }
    if (typeFilter !== "all") {
      filtered = filtered.filter(b => (b.build_types?.type_name || "").toLowerCase() === typeFilter.toLowerCase())
    }
    switch (sortBy) {
      case "recent": return [...filtered].sort((a, b) => new Date(b.date_created).getTime() - new Date(a.date_created).getTime())
      case "price-low": return [...filtered].sort((a, b) => (a.totalPrice || 0) - (b.totalPrice || 0))
      case "price-high": return [...filtered].sort((a, b) => (b.totalPrice || 0) - (a.totalPrice || 0))
      case "likes": return [...filtered].sort((a, b) => (b.likes || 0) - (a.likes || 0))
      default: return [...filtered].sort((a, b) => (b.likes || 0) - (a.likes || 0))
    }
  }

  const filteredBuilds = getFilteredBuilds()
  const formatNumber = (num: number) => num.toLocaleString()

  if (loading && builds.length === 0) {
    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>
    )
  }

  const buildTypeOptions = ["all", ...Array.from(new Set(builds.map(b => b.build_types?.type_name).filter(Boolean) as string[]))]

  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 max-w-6xl">
        {error && (
          <div className="mb-4 p-4 bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800 rounded-lg">
            <p className="text-red-800 dark:text-red-200">{error}</p>
          </div>
        )}

        {/* Page header — Community Builds */}
        <div className="mb-8">
          <h1 className="text-3xl md:text-4xl font-bold text-slate-900 dark:text-white mb-2">
            Community Builds
          </h1>
          <p className="text-slate-600 dark:text-slate-400 max-w-2xl mb-6">
            Discover builds from other builders. Get inspiration, compare specs, and clone builds to customize in the PC Builder.
          </p>
          <div className="flex flex-wrap items-center gap-3">
            <Button asChild className="bg-blue-500 hover:bg-blue-600 text-white">
              <Link href="/builder">
                <Plus className="h-4 w-4 mr-2" />
                Create your build
              </Link>
            </Button>
            <Button variant="outline" asChild>
              <Link href="/builder">Open PC Builder</Link>
            </Button>
          </div>
        </div>

        {/* Stats strip — card style */}
        <div className="grid grid-cols-1 sm:grid-cols-3 gap-4 mb-8">
          <div className="rounded-xl border border-slate-200 dark:border-slate-700 bg-white dark:bg-slate-800/50 p-4 flex items-center gap-4">
            <div className="rounded-lg bg-indigo-500/10 p-3">
              <Users className="h-6 w-6 text-indigo-600 dark:text-indigo-400" />
            </div>
            <div>
              <p className="text-2xl font-bold text-slate-900 dark:text-white">{formatNumber(statistics.totalBuilders)}</p>
              <p className="text-sm text-slate-600 dark:text-slate-400">Builders</p>
            </div>
          </div>
          <div className="rounded-xl border border-slate-200 dark:border-slate-700 bg-white dark:bg-slate-800/50 p-4 flex items-center gap-4">
            <div className="rounded-lg bg-emerald-500/10 p-3">
              <Cpu className="h-6 w-6 text-emerald-600 dark:text-emerald-400" />
            </div>
            <div>
              <p className="text-2xl font-bold text-slate-900 dark:text-white">{formatNumber(statistics.totalBuilds)}</p>
              <p className="text-sm text-slate-600 dark:text-slate-400">Builds</p>
            </div>
          </div>
          <div className="rounded-xl border border-slate-200 dark:border-slate-700 bg-white dark:bg-slate-800/50 p-4 flex items-center gap-4">
            <div className="rounded-lg bg-blue-500/10 p-3">
              <Heart className="h-6 w-6 text-blue-600 dark:text-blue-400" />
            </div>
            <div>
              <p className="text-2xl font-bold text-slate-900 dark:text-white">{formatNumber(statistics.totalLikes)}</p>
              <p className="text-sm text-slate-600 dark:text-slate-400">Likes</p>
            </div>
          </div>
        </div>

        <Tabs value={activeTab} onValueChange={(v) => setActiveTab(v as "browse" | "compare")} className="mb-8">
          <TabsList className="grid w-full grid-cols-2 max-w-md">
            <TabsTrigger value="browse">Browse Builds</TabsTrigger>
            <TabsTrigger value="compare">Compare Builds</TabsTrigger>
          </TabsList>

          {/* Browse Tab */}
          <TabsContent value="browse" className="space-y-6">
        <div className="rounded-xl border border-slate-200 dark:border-slate-700 bg-white dark:bg-slate-800/30 p-4 mb-6">
          <p className="text-sm font-medium text-slate-700 dark:text-slate-300 mb-3">Search & filters</p>
          <div className="flex flex-col gap-3">
            <div className="relative">
              <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-slate-400" />
              <Input
                placeholder="Search by build name, type, or creator..."
                className="pl-10"
                value={searchTerm}
                onChange={(e) => setSearchTerm(e.target.value)}
              />
            </div>
            <div className="flex flex-wrap gap-2">
              <Select value={sortBy} onValueChange={setSortBy}>
                <SelectTrigger className="w-full sm:w-44">
                  <SelectValue placeholder="Sort by" />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="popular">Most Popular</SelectItem>
                  <SelectItem value="recent">Most Recent</SelectItem>
                  <SelectItem value="likes">Most Liked</SelectItem>
                  <SelectItem value="price-low">Price: Low to High</SelectItem>
                  <SelectItem value="price-high">Price: High to Low</SelectItem>
                </SelectContent>
              </Select>
              <Select value={priceFilter} onValueChange={setPriceFilter}>
                <SelectTrigger className="w-full sm:w-40">
                  <SelectValue placeholder="Price" />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="all">All Prices</SelectItem>
                  <SelectItem value="budget">{PRICE_RANGES.budget.label}</SelectItem>
                  <SelectItem value="mid">{PRICE_RANGES.mid.label}</SelectItem>
                  <SelectItem value="high">{PRICE_RANGES.high.label}</SelectItem>
                </SelectContent>
              </Select>
              <Select value={typeFilter} onValueChange={setTypeFilter}>
                <SelectTrigger className="w-full sm:w-40">
                  <SelectValue placeholder="Type" />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="all">All Types</SelectItem>
                  {buildTypeOptions.filter(t => t !== "all").map((typeName) => (
                    <SelectItem key={typeName} value={typeName}>
                      {typeName}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>
          </div>
        </div>

        <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-5">
          {filteredBuilds.map((build) => {
            const creator = build.users
            const isLiked = likedBuilds.includes(build.build_id)
            const profileHref =
              user && creator?.user_id === user.user_id
                ? `/profile`
                : `/profile/${creator?.user_id}`;
            const cpuComponent = build.components?.find(
              (c: any) => c.category_name === 'CPU'
            )

            const gpuComponent = build.components?.find(
              (c: any) => c.category_name === 'GPU'
            )


            const isPopular = (build.likes || 0) >= 5
            const componentCount = build.components?.length || 0

            return (
              <Card
                key={build.build_id}
                className="border-slate-200 dark:border-slate-700 hover:shadow-lg hover:border-slate-300 dark:hover:border-slate-600 transition-all duration-200 group flex flex-col"
              >
                <CardHeader className="pb-3">
                  <div className="flex items-start justify-between gap-3">
                    <div className="flex-1 min-w-0">
                      <div className="flex items-center gap-2 flex-wrap">
                        <CardTitle className="text-lg group-hover:text-blue-600 dark:group-hover:text-blue-400 transition-colors truncate">
                          {build.build_name}
                        </CardTitle>
                        {isPopular && (
                          <Badge className="bg-amber-500/90 text-white text-xs shrink-0">Popular</Badge>
                        )}
                      </div>
                      <div className="flex items-center gap-2 mt-2">
                        <Link href={profileHref} className="flex items-center gap-2 rounded-full hover:bg-slate-100 dark:hover:bg-slate-800 pr-2 transition-colors">
                          <Avatar className="h-6 w-6 cursor-pointer ring-2 ring-slate-200 dark:ring-slate-600">
                            {creator?.avatar_url ? (
                              <AvatarImage src={creator?.avatar_url} />
                            ) : (
                              <AvatarFallback className="text-xs">
                                {creator?.user_name ? creator.user_name.charAt(0).toUpperCase() : "?"}
                              </AvatarFallback>
                            )}
                          </Avatar>
                          <span className="text-sm text-slate-600 dark:text-slate-400 truncate">
                            {creator?.user_name || "Unknown"}
                          </span>
                        </Link>
                      </div>
                    </div>
                    <div className="text-right flex flex-col items-end gap-1 shrink-0">
                      <Badge variant="secondary" className="font-semibold text-sm">
                        {formatCurrency(build.totalPrice || 0)}
                      </Badge>
                      <span className="text-xs text-slate-500">
                        {componentCount} part{componentCount !== 1 ? "s" : ""}
                      </span>
                      <div className="flex items-center gap-1 text-xs text-slate-500">
                        <Eye className="h-3 w-3" />
                        <span>{(build.views || 0).toLocaleString()}</span>
                      </div>
                    </div>
                  </div>
                </CardHeader>

                <CardContent className="space-y-4 flex-1 flex flex-col pt-0">
                  <p className="text-sm text-slate-600 dark:text-slate-400 line-clamp-2 min-h-[2.5rem]">
                    {build?.description || "PC build shared by the community."}
                  </p>

                  <div className="flex flex-wrap gap-1.5">
                    <Badge variant="outline" className="text-xs">
                      {build.build_types?.type_name || "Build"}
                    </Badge>
                  </div>

                  <div className="space-y-1.5 text-xs">
                    {cpuComponent && (
                      <div className="flex items-center gap-2 text-slate-600 dark:text-slate-400 truncate">
                        <Cpu className="h-3.5 w-3.5 text-blue-500 shrink-0" />
                        <span className="truncate">{cpuComponent?.component_name}</span>
                      </div>
                    )}
                    {gpuComponent && (
                      <div className="flex items-center gap-2 text-slate-600 dark:text-slate-400 truncate">
                        <Monitor className="h-3.5 w-3.5 text-green-500 shrink-0" />
                        <span className="truncate">{gpuComponent?.component_name}</span>
                      </div>
                    )}
                  </div>

                  <div className="mt-auto pt-4 border-t border-slate-100 dark:border-slate-700 space-y-3">
                    <div className="flex items-center justify-between">
                      <div className="flex items-center gap-2">
                        <Button
                          variant="ghost"
                          size="sm"
                          className={`h-8 px-2 flex items-center gap-1 text-sm ${
                            isLiked ? "text-red-500 hover:text-red-600" : "text-slate-500 hover:text-red-500"
                          }`}
                          onClick={() => toggleLike(build.build_id)}
                        >
                          <Heart className={`h-4 w-4 ${isLiked ? "fill-current" : ""}`} />
                          <span>{build.likes || 0}</span>
                        </Button>
                        <Button variant="ghost" size="sm" className="h-8 px-2 text-slate-500 hover:text-blue-500" asChild>
                          <Link href={`/builds/${build.build_id}`}>
                            <MessageCircle className="h-4 w-4" />
                            <span>{build.comments || 0}</span>
                          </Link>
                        </Button>
                        <Button
                          variant="ghost"
                          size="sm"
                          className="h-8 px-2 text-slate-500 hover:text-green-500"
                          onClick={() => {
                            setShareUrl(typeof window !== "undefined" ? `${window.location.origin}/builds/${build.build_id}` : "")
                            setSharePopupOpen(true)
                          }}
                        >
                          <Share className="h-4 w-4" />
                        </Button>
                      </div>
                    </div>
                    <div className="flex gap-2">
                      <Button size="sm" className="flex-1 bg-blue-500 hover:bg-blue-600 text-white" asChild>
                        <Link href={`/builds/${build.build_id}`}>View Details</Link>
                      </Button>
                      <Button
                        size="sm"
                        variant="outline"
                        className="shrink-0"
                        onClick={() => {
                          if (selectedBuildsForCompare.length >= 3) {
                            swal.info("Limit reached", "You can compare up to 3 builds at once")
                            return
                          }
                          if (selectedBuildsForCompare.some(b => b.build_id === build.build_id)) {
                            swal.info("Already added", "This build is already in the comparison")
                            return
                          }
                          setSelectedBuildsForCompare([...selectedBuildsForCompare, build])
                          setActiveTab("compare")
                        }}
                      >
                        <BarChart3 className="h-3.5 w-3.5" />
                      </Button>
                    </div>
                  </div>
                </CardContent>
              </Card>
            )
          })}
        </div>

        {filteredBuilds.length === 0 && !loading && (
          <div className="rounded-2xl border border-dashed border-slate-300 dark:border-slate-600 bg-slate-50/50 dark:bg-slate-800/30 py-16 px-6 text-center">
            <div className="rounded-full bg-slate-200/80 dark:bg-slate-700/80 p-4 w-fit mx-auto mb-4">
              <Cpu className="h-10 w-10 text-slate-500 dark:text-slate-400" />
            </div>
            <h3 className="text-xl font-semibold text-slate-900 dark:text-white mb-2">No builds match your filters</h3>
            <p className="text-slate-600 dark:text-slate-400 max-w-sm mx-auto mb-6">
              Try different search terms, clear the type or price filter, or be the first to share a build.
            </p>
            <div className="flex flex-wrap justify-center gap-3">
              <Button
                variant="outline"
                onClick={() => {
                  setSearchTerm("")
                  setTypeFilter("all")
                  setPriceFilter("all")
                }}
              >
                Clear filters
              </Button>
              <Button asChild className="bg-blue-500 hover:bg-blue-600 text-white">
                <Link href="/builder">Create your build</Link>
              </Button>
            </div>
          </div>
        )}

        {filteredBuilds.length > 0 && builds.length >= buildsLimit && (
          <div className="flex justify-center pt-6">
            <Button
              variant="outline"
              onClick={() => setBuildsLimit(prev => prev + 30)}
              disabled={loading}
            >
              {loading ? "Loading..." : "Load more builds"}
            </Button>
          </div>
        )}
          </TabsContent>

          {/* Compare Tab */}
          <TabsContent value="compare" className="space-y-6">
            {selectedBuildsForCompare.length === 0 ? (
              <Card>
                <CardHeader>
                  <CardTitle>Select Builds to Compare</CardTitle>
                  <CardContent>
                    <p className="text-slate-600 dark:text-slate-400 mb-4">
                      Choose builds from the Browse tab to compare them side by side
                    </p>
                    <Button onClick={() => setActiveTab("browse")}>
                      Browse Builds
                    </Button>
                  </CardContent>
                </CardHeader>
              </Card>
            ) : (
              <div className="space-y-6">
                <Card>
                  <CardHeader>
                    <div className="flex items-center justify-between">
                      <div>
                        <CardTitle>Comparing {selectedBuildsForCompare.length} Builds</CardTitle>
                        <p className="text-sm text-slate-600 dark:text-slate-400 mt-1">
                          Analyze differences in specs, performance, and cost
                        </p>
                      </div>
                      <div className="flex items-center gap-2">
                        <Button variant="outline" size="sm" onClick={() => setSelectedBuildsForCompare([])}>
                          <X className="h-4 w-4 mr-2" />
                          Clear All
                        </Button>
                        <Button size="sm" onClick={() => setActiveTab("browse")}>
                          Add More
                        </Button>
                      </div>
                    </div>
                  </CardHeader>
                  <CardContent>
                    <div className="flex flex-wrap gap-2">
                      {selectedBuildsForCompare.map((build, index) => (
                        <div key={build.build_id} className="flex items-center gap-2 bg-slate-100 dark:bg-slate-800 rounded-lg px-3 py-2">
                          <Badge variant={index === 0 ? "default" : "secondary"}>
                            Build {index + 1}
                          </Badge>
                          <span className="font-medium">{build.build_name}</span>
                          <Button
                            size="sm"
                            variant="ghost"
                            onClick={() => setSelectedBuildsForCompare(selectedBuildsForCompare.filter(b => b.build_id !== build.build_id))}
                            className="h-6 w-6 p-0"
                          >
                            <X className="h-3 w-3" />
                          </Button>
                        </div>
                      ))}
                    </div>
                  </CardContent>
                </Card>

                <Tabs value={compareActiveTab} onValueChange={setCompareActiveTab}>
                  <TabsList className="grid w-full grid-cols-4">
                    <TabsTrigger value="overview">Overview</TabsTrigger>
                    <TabsTrigger value="components">Components</TabsTrigger>
                    <TabsTrigger value="price">Price</TabsTrigger>
                    <TabsTrigger value="specs">Specs</TabsTrigger>
                  </TabsList>

                  <TabsContent value="overview" className="space-y-6">
                    <div className="grid lg:grid-cols-3 gap-6">
                      {selectedBuildsForCompare.map((build, index) => (
                        <Card key={build.build_id} className="border-slate-200 dark:border-slate-700">
                          <CardHeader>
                            <CardTitle className="text-lg">{build.build_name}</CardTitle>
                            <p className="text-sm text-slate-600 dark:text-slate-400">{build.description || 'PC Build'}</p>
                          </CardHeader>
                          <CardContent className="space-y-4">
                            <div className="flex items-center justify-between">
                              <span className="text-sm text-slate-600 dark:text-slate-400">Total Price</span>
                              <span className="text-xl font-bold text-blue-600">{formatCurrency(build.totalPrice || 0)}</span>
                            </div>
                            <div className="flex items-center justify-between">
                              <span className="text-sm text-slate-600 dark:text-slate-400">Likes</span>
                              <span className="font-medium">{build.likes || 0}</span>
                            </div>
                            <div className="flex items-center justify-between">
                              <span className="text-sm text-slate-600 dark:text-slate-400">Views</span>
                              <span className="font-medium">{(build.views || 0).toLocaleString()}</span>
                            </div>
                            <div className="flex items-center justify-between">
                              <span className="text-sm text-slate-600 dark:text-slate-400">Components</span>
                              <span className="font-medium">{build.components?.length || 0}</span>
                            </div>
                          </CardContent>
                        </Card>
                      ))}
                    </div>
                  </TabsContent>

                  <TabsContent value="price" className="space-y-6">
                    <Card>
                      <CardHeader>
                        <CardTitle className="flex items-center gap-2">
                          <DollarSign className="h-5 w-5" />
                          Price Comparison
                        </CardTitle>
                      </CardHeader>
                      <CardContent>
                        <div className="space-y-4">
                          {selectedBuildsForCompare.map((build, index) => {
                            const maxPrice = Math.max(...selectedBuildsForCompare.map(b => b.totalPrice || 0))
                            const pricePercentage = maxPrice > 0 ? ((build.totalPrice || 0) / maxPrice) * 100 : 0
                            return (
                              <div key={build.build_id} className="space-y-2">
                                <div className="flex items-center justify-between">
                                  <span className="font-medium">{build.build_name}</span>
                                  <span className="text-lg font-bold">{formatCurrency(build.totalPrice || 0)}</span>
                                </div>
                                <div className="w-full bg-slate-200 dark:bg-slate-700 rounded-full h-3">
                                  <div
                                    className="bg-blue-600 h-3 rounded-full"
                                    style={{ width: `${pricePercentage}%` }}
                                  />
                                </div>
                              </div>
                            )
                          })}
                        </div>
                      </CardContent>
                    </Card>
                  </TabsContent>

                  <TabsContent value="components" className="space-y-6">
                    <Card>
                      <CardHeader>
                        <CardTitle>Component Comparison</CardTitle>
                      </CardHeader>
                      <CardContent>
                        <div className="overflow-x-auto">
                          <table className="w-full">
                            <thead>
                              <tr className="border-b">
                                <th className="text-left p-2">Component</th>
                                {selectedBuildsForCompare.map((build, index) => (
                                  <th key={build.build_id} className="text-left p-2">
                                    Build {index + 1}
                                  </th>
                                ))}
                              </tr>
                            </thead>
                            <tbody>
                              {[
                                { display: 'CPU', dbNames: ['CPU'] },
                                { display: 'GPU', dbNames: ['GPU'] },
                                { display: 'Memory', dbNames: ['Memory', 'RAM'] },
                                { display: 'Storage', dbNames: ['Storage'] }
                              ].map(({ display, dbNames }) => (
                                <tr key={display} className="border-b">
                                  <td className="p-2 font-medium">{display}</td>
                                  {selectedBuildsForCompare.map((build) => {
                                    const component = build.components?.find((bc: any) => {
                                      const categoryName = bc.components?.component_categories?.category_name
                                      return categoryName && dbNames.includes(categoryName)
                                    })
                                    return (
                                      <td key={build.build_id} className="p-2">
                                        {component?.components?.component_name || 'N/A'}
                                      </td>
                                    )
                                  })}
                                </tr>
                              ))}
                            </tbody>
                          </table>
                        </div>
                      </CardContent>
                    </Card>
                  </TabsContent>

                  <TabsContent value="specs" className="space-y-6">
                    <Card>
                      <CardHeader>
                        <CardTitle>Detailed Specifications</CardTitle>
                      </CardHeader>
                      <CardContent>
                        <div className="grid md:grid-cols-2 lg:grid-cols-3 gap-6">
                          {selectedBuildsForCompare.map((build, index) => (
                            <Card key={build.build_id} className="border-slate-200 dark:border-slate-700">
                              <CardHeader>
                                <CardTitle className="text-lg">{build.build_name}</CardTitle>
                              </CardHeader>
                              <CardContent className="space-y-2">
                                <div className="text-sm">
                                  <span className="font-medium">Price: </span>
                                  <span>{formatCurrency(build.totalPrice || 0)}</span>
                                </div>
                                <div className="text-sm">
                                  <span className="font-medium">Components: </span>
                                  <span>{build.components?.length || 0}</span>
                                </div>
                                <div className="text-sm">
                                  <span className="font-medium">Type: </span>
                                  <span>{build.build_types?.type_name || 'N/A'}</span>
                                </div>
                                <div className="text-sm">
                                  <span className="font-medium">Created: </span>
                                  <span>{new Date(build.date_created).toLocaleDateString()}</span>
                                </div>
                              </CardContent>
                            </Card>
                          ))}
                        </div>
                      </CardContent>
                    </Card>
                  </TabsContent>
                </Tabs>
              </div>
            )}
          </TabsContent>
        </Tabs>
      </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-xl shadow-xl p-6 w-full max-w-sm mx-4">
            <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 to share this build with others.
            </p>
            <div className="flex 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 variant="outline" className="w-full" onClick={() => setSharePopupOpen(false)}>
              Close
            </Button>
          </div>
        </div>
      )}
    </div>
  )
}
