"use client" import { useState, useEffect } from "react" import { useAuth } from "@/contexts/auth-context" import { useCompetition } from "@/contexts/competition-context" import { Search, Heart, Eye, Trophy, Calendar, Users, Target, Lightbulb, MessageSquare, ImageIcon, Mic, TrendingUp, Brain, Zap, Crown, ChevronLeft, ChevronRight, ThumbsUp, } from "lucide-react" import { Button } from "@/components/ui/button" import { Input } from "@/components/ui/input" import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card" import { Badge } from "@/components/ui/badge" import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select" import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar" import { LikeButton } from "@/components/like-button" import { AppDetailDialog } from "@/components/app-detail-dialog" import { TeamDetailDialog } from "@/components/competition/team-detail-dialog" // AI applications data - empty for production const aiApps: any[] = [] // Teams data - empty for production const mockTeams: any[] = [] export function PopularityRankings() { const { user, getLikeCount, getViewCount } = useAuth() const { competitions, currentCompetition, setCurrentCompetition, judges } = useCompetition() const [searchTerm, setSearchTerm] = useState("") const [selectedDepartment, setSelectedDepartment] = useState("all") const [selectedType, setSelectedType] = useState("all") const [selectedCompetitionType, setSelectedCompetitionType] = useState("all") const [selectedApp, setSelectedApp] = useState(null) const [showAppDetail, setShowAppDetail] = useState(false) const [selectedTeam, setSelectedTeam] = useState(null) const [showTeamDetail, setShowTeamDetail] = useState(false) const [individualCurrentPage, setIndividualCurrentPage] = useState(0) const [teamCurrentPage, setTeamCurrentPage] = useState(0) // 新增狀態 const [competitionApps, setCompetitionApps] = useState([]) const [competitionTeams, setCompetitionTeams] = useState([]) const [competitionJudges, setCompetitionJudges] = useState([]) const [isLoading, setIsLoading] = useState(false) const ITEMS_PER_PAGE = 3 // 載入當前競賽的數據 useEffect(() => { if (currentCompetition) { loadCompetitionData(currentCompetition.id) } else { // 如果沒有當前競賽,清空數據 setCompetitionApps([]) setCompetitionTeams([]) setCompetitionJudges([]) } }, [currentCompetition]) const loadCompetitionData = async (competitionId: string) => { setIsLoading(true) try { // 並行載入競賽的應用、團隊和評審數據 const [appsResponse, teamsResponse, judgesResponse] = await Promise.all([ fetch(`/api/competitions/${competitionId}/apps`), // 移除 competitionType 參數,載入所有應用 fetch(`/api/competitions/${competitionId}/teams`), fetch(`/api/competitions/${competitionId}/judges`) ]) const [appsData, teamsData, judgesData] = await Promise.all([ appsResponse.json(), teamsResponse.json(), judgesResponse.json() ]) if (appsData.success) { // 合併個人應用和團隊應用 const allApps = appsData.data.apps || [] console.log('📱 載入的應用數據:', allApps) setCompetitionApps(allApps) } if (teamsData.success) { const teams = teamsData.data.teams || [] console.log('👥 載入的團隊數據:', teams) setCompetitionTeams(teams) } if (judgesData.success) { const judges = judgesData.data.judges || [] console.log('👨‍⚖️ 載入的評審數據:', judges) setCompetitionJudges(judges) } } catch (error) { console.error('載入競賽數據失敗:', error) } finally { setIsLoading(false) } } // Filter apps based on search criteria const filteredApps = competitionApps.filter((app) => { const matchesSearch = app.name.toLowerCase().includes(searchTerm.toLowerCase()) || app.description.toLowerCase().includes(searchTerm.toLowerCase()) || app.creator.toLowerCase().includes(searchTerm.toLowerCase()) const matchesDepartment = selectedDepartment === "all" || app.department === selectedDepartment const matchesType = selectedType === "all" || app.type === selectedType const matchesCompetitionType = selectedCompetitionType === "all" || app.competitionType === selectedCompetitionType return matchesSearch && matchesDepartment && matchesType && matchesCompetitionType }) // Sort apps by like count (popularity) and group by competition type const sortedApps = filteredApps.sort((a, b) => { return (b.likes || 0) - (a.likes || 0) }) // Group apps by competition type const individualApps = sortedApps.filter((app) => app.competitionType === "individual") const teamApps = sortedApps.filter((app) => app.competitionType === "team") const getTypeColor = (type: string) => { const colors = { 文字處理: "bg-blue-100 text-blue-800 border-blue-200", 圖像生成: "bg-purple-100 text-purple-800 border-purple-200", 語音辨識: "bg-green-100 text-green-800 border-green-200", 推薦系統: "bg-orange-100 text-orange-800 border-orange-200", } return colors[type as keyof typeof colors] || "bg-gray-100 text-gray-800 border-gray-200" } const getCompetitionTypeIcon = (type: string) => { switch (type) { case "individual": return case "team": return case "proposal": return case "mixed": return default: return } } const getCompetitionTypeText = (type: string) => { switch (type) { case "individual": return "個人賽" case "team": return "團隊賽" case "proposal": return "提案賽" case "mixed": return "混合賽" default: return "競賽" } } const getCompetitionTypeColor = (type: string) => { switch (type) { case "individual": return "bg-blue-100 text-blue-800 border-blue-200" case "team": return "bg-green-100 text-green-800 border-green-200" case "proposal": return "bg-purple-100 text-purple-800 border-purple-200" case "mixed": return "bg-gradient-to-r from-blue-100 via-green-100 to-purple-100 text-gray-800 border-gray-200" default: return "bg-gray-100 text-gray-800 border-gray-200" } } const handleOpenAppDetail = (app: any) => { setSelectedApp(app) setShowAppDetail(true) } const handleOpenTeamDetail = (team: any) => { setSelectedTeam(team) setShowTeamDetail(true) } const renderCompetitionSection = (apps: any[], title: string, competitionType: string) => { if (apps.length === 0) { return null } const currentPage = competitionType === "individual" ? individualCurrentPage : teamCurrentPage const setCurrentPage = competitionType === "individual" ? setIndividualCurrentPage : setTeamCurrentPage const totalPages = Math.ceil(apps.length / ITEMS_PER_PAGE) const startIndex = currentPage * ITEMS_PER_PAGE const endIndex = startIndex + ITEMS_PER_PAGE const currentApps = apps.slice(startIndex, endIndex) return (
{competitionType === "individual" ? ( ) : ( )} {title} {currentCompetition?.name || "暫無進行中的競賽"} - {title}人氣排名 (共 {apps.length} 個應用)
{getCompetitionTypeIcon(competitionType)} {getCompetitionTypeText(competitionType)}
{/* Page indicator */} {totalPages > 1 && (
顯示第 {startIndex + 1}-{Math.min(endIndex, apps.length)} 名,共 {apps.length} 個應用
{Array.from({ length: totalPages }).map((_, index) => (
))}
)} {/* Carousel Container */}
{/* Left Arrow */} {totalPages > 1 && currentPage > 0 && ( )} {/* Right Arrow */} {totalPages > 1 && currentPage < totalPages - 1 && ( )} {/* Apps Grid */}
{currentApps.map((app, index) => { const likes = getLikeCount(app.id.toString()) const views = getViewCount(app.id.toString()) const globalRank = startIndex + index + 1 return (
{/* Numbered Badge */}
{globalRank}
{/* App Icon */}

{app.name}

by {app.creator}

{app.type} {app.department}
{/* Description - flexible height */}

{app.description}

{/* Stats */}
{views} 次瀏覽
{globalRank <= 3 && (
人氣冠軍
)}
{/* Action Buttons - Always at bottom with consistent positioning */}
{/* Enhanced Like Button */}
{/* View Details Button */}
) })}
) } const renderTeamCompetitionSection = (teams: any[], title: string) => { if (teams.length === 0) { return null } // 團隊已經從 API 獲取了人氣分數,直接使用 const teamsWithScores = teams.sort((a, b) => b.popularityScore - a.popularityScore) const currentPage = teamCurrentPage const setCurrentPage = setTeamCurrentPage const totalPages = Math.ceil(teamsWithScores.length / ITEMS_PER_PAGE) const startIndex = currentPage * ITEMS_PER_PAGE const endIndex = startIndex + ITEMS_PER_PAGE const currentTeams = teamsWithScores.slice(startIndex, endIndex) return (
{title} {currentCompetition?.name || "暫無進行中的競賽"} - {title}人氣排名 (共 {teamsWithScores.length} 個團隊)
團隊賽
{/* Page indicator */} {totalPages > 1 && (
顯示第 {startIndex + 1}-{Math.min(endIndex, teamsWithScores.length)} 名,共 {teamsWithScores.length}{" "} 個團隊
{Array.from({ length: totalPages }).map((_, index) => (
))}
)} {/* Carousel Container */}
{/* Left Arrow */} {totalPages > 1 && currentPage > 0 && ( )} {/* Right Arrow */} {totalPages > 1 && currentPage < totalPages - 1 && ( )} {/* Teams Grid */}
{currentTeams.map((team, index) => { const globalRank = startIndex + index + 1 const leader = team.members.find((m: any) => m.id === team.leader) return (
{/* Numbered Badge */}
{globalRank}
{/* Team Icon */}

{team.name}

隊長:{leader?.name}

團隊賽 {team.department}
{/* Team Members */}
團隊成員 ({team.members.length}人)
{team.members.slice(0, 3).map((member: any) => (
{member.name[0]}
{member.name} ({member.role})
))} {team.members.length > 3 && (
還有 {team.members.length - 3} 位成員...
)}
{/* Apps Info */}
提交應用
{team.totalApps}
應用數量
{team.maxLikes}
最高按讚
{/* Stats */}
{team.totalViews} 次瀏覽
{globalRank <= 3 && (
人氣前三
)}
{/* Popularity Score */}
{team.popularityScore}
人氣指數
{team.totalApps} 個應用 × {team.maxLikes} 最高按讚
{/* Action Buttons */}
{team.totalLikes || 0} 總按讚
) })}
) } return (
{/* Competition Info */}
競賽人氣排行 {currentCompetition?.name || "暫無進行中的競賽"} - 基於用戶按讚數的即時人氣排名
{currentCompetition && (
{currentCompetition.year}年{currentCompetition.month}月
{getCompetitionTypeIcon(currentCompetition.type)} {getCompetitionTypeText(currentCompetition.type)}
{currentCompetition.type === 'team' ? `${competitionTeams.length} 個參賽團隊` : `${filteredApps.length} 個參賽應用`}
{currentCompetition.status === "completed" ? "已完成" : currentCompetition.status === "judging" ? "評審中" : currentCompetition.status === "active" ? "進行中" : "即將開始"}

{currentCompetition.description}

)}
{/* Judge Panel */} 評審團 專業評審團隊 {isLoading ? (

載入評審團中...

) : competitionJudges.length > 0 ? (
{competitionJudges.map((judge) => (
{judge.name[0]}

{judge.name}

{judge.title}

{judge.expertise.slice(0, 2).map((skill) => ( {skill} ))}
))}
) : (

暫無評審團成員

)}
{/* Search and Filter Section */} 篩選條件 根據部門、應用類型、競賽類型或關鍵字篩選參賽應用
setSearchTerm(e.target.value)} className="pl-10" />
{/* Competition Rankings */} {currentCompetition ? (
{/* Individual Competition Section */} {(selectedCompetitionType === "all" || selectedCompetitionType === "individual") && renderCompetitionSection(individualApps, "個人賽", "individual")} {/* Team Competition Section */} {(selectedCompetitionType === "all" || selectedCompetitionType === "team") && currentCompetition?.type === "team" && renderTeamCompetitionSection( competitionTeams.filter( (team) => { const matchesSearch = searchTerm === "" || team.name.toLowerCase().includes(searchTerm.toLowerCase()) || team.members?.some((member: any) => member.name.toLowerCase().includes(searchTerm.toLowerCase())); const matchesDepartment = selectedDepartment === "all" || team.department === selectedDepartment; return matchesSearch && matchesDepartment; } ), "團隊賽", )} {/* No Results */} {filteredApps.length === 0 && competitionTeams.length === 0 && (

{currentCompetition?.type === 'team' ? '沒有找到符合條件的團隊' : '沒有找到符合條件的應用'}

請調整篩選條件或清除搜尋關鍵字

)}
) : (

請選擇競賽

選擇一個競賽來查看人氣排行榜

)} {/* App Detail Dialog */} {selectedApp && } {/* Team Detail Dialog */} {selectedTeam && }
) }