"use client" import { useState, useEffect } from "react" import { useAuth } from "@/contexts/auth-context" import { useCompetition } from "@/contexts/competition-context" import { Search, Star, Heart, Eye, Brain, MessageSquare, ImageIcon, Mic, TrendingUp, Zap, Settings, Trophy, ChevronLeft, ChevronRight, Award, Medal, Target, Users, Lightbulb, ArrowLeft, Plus, X, Database, BarChart3, Camera, Smartphone, Monitor, Globe, FileText, Bot, } 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 { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs" import { LoginDialog } from "@/components/auth/login-dialog" import { RegisterDialog } from "@/components/auth/register-dialog" import { UserMenu } from "@/components/auth/user-menu" import { FavoriteButton } from "@/components/favorite-button" import { FavoritesPage } from "@/components/favorites-page" import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from "@/components/ui/dialog" import { AppDetailDialog } from "@/components/app-detail-dialog" import { ForgotPasswordDialog } from "@/components/auth/forgot-password-dialog" import { PopularityRankings } from "@/components/competition/popularity-rankings" import { CompetitionDetailDialog } from "@/components/competition/competition-detail-dialog" import { AwardDetailDialog } from "@/components/competition/award-detail-dialog" import { LikeButton } from "@/components/like-button" // AI applications data - will be loaded from API // Pagination component interface PaginationProps { currentPage: number totalPages: number onPageChange: (page: number) => void } function Pagination({ currentPage, totalPages, onPageChange }: PaginationProps) { const getVisiblePages = () => { const delta = 2 const range = [] const rangeWithDots = [] for (let i = Math.max(2, currentPage - delta); i <= Math.min(totalPages - 1, currentPage + delta); i++) { range.push(i) } if (currentPage - delta > 2) { rangeWithDots.push(1, "...") } else { rangeWithDots.push(1) } rangeWithDots.push(...range) if (currentPage + delta < totalPages - 1) { rangeWithDots.push("...", totalPages) } else if (totalPages > 1) { rangeWithDots.push(totalPages) } return rangeWithDots } const visiblePages = getVisiblePages() return (
{visiblePages.map((page, index) => (
{page === "..." ? ( ... ) : ( )}
))}
) } export default function AIShowcasePlatform() { const { user, addToRecentApps, getAppLikes, incrementViewCount, getViewCount, getAppRating, canAccessAdmin, } = useAuth() const { competitions, awards, getAwardsByYear, getCompetitionRankings, loadingAwards, getAvailableYears } = useCompetition() const [showLogin, setShowLogin] = useState(false) const [showRegister, setShowRegister] = useState(false) const [searchTerm, setSearchTerm] = useState("") const [selectedDepartment, setSelectedDepartment] = useState("all") const [selectedType, setSelectedType] = useState("all") const [showFavorites, setShowFavorites] = useState(false) const [selectedApp, setSelectedApp] = useState(null) const [showAppDetail, setShowAppDetail] = useState(false) const [showForgotPassword, setShowForgotPassword] = useState(false) const [currentPage, setCurrentPage] = useState(1) const [showCompetition, setShowCompetition] = useState(false) const appsPerPage = 6 // 新增狀態管理 const [aiApps, setAiApps] = useState([]) const [isLoadingApps, setIsLoadingApps] = useState(true) const [totalPages, setTotalPages] = useState(0) const [totalApps, setTotalApps] = useState(0) const [departments, setDepartments] = useState<{value: string, label: string, count: number}[]>([]) const [types, setTypes] = useState<{value: string, label: string, count: number}[]>([]) const [categories, setCategories] = useState<{value: string, label: string, count: number}[]>([]) // Competition page states const [selectedCompetitionTypeFilter, setSelectedCompetitionTypeFilter] = useState("all") const [selectedMonthFilter, setSelectedMonthFilter] = useState("all") const [selectedAwardCategory, setSelectedAwardCategory] = useState("all") const [selectedYear, setSelectedYear] = useState(2024) const [searchQuery, setSearchQuery] = useState("") const [showCompetitionDetail, setShowCompetitionDetail] = useState(false) const [selectedRanking, setSelectedRanking] = useState(null) const [selectedCompetitionType, setSelectedCompetitionType] = useState<"individual" | "team" | "proposal">( "individual", ) const [showAwardDetail, setShowAwardDetail] = useState(false) const [selectedAward, setSelectedAward] = useState(null) // 添加頁面調試資訊 console.log('🏠 主頁面渲染:', { awardsCount: awards.length, selectedAward: selectedAward ? selectedAward.id : null, showAwardDetail }); // 動態設定初始年份 useEffect(() => { if (awards.length > 0 && selectedYear === 2024) { const availableYears = getAvailableYears(); if (availableYears.length > 0) { setSelectedYear(availableYears[0]); console.log('🎯 自動設定年份為:', availableYears[0]); } } }, [awards, selectedYear, getAvailableYears]); // 載入應用數據 const loadApps = async () => { try { setIsLoadingApps(true) const params = new URLSearchParams({ page: currentPage.toString(), limit: appsPerPage.toString(), search: searchTerm, department: selectedDepartment, type: selectedType }) const response = await fetch(`/api/apps?${params}`) const data = await response.json() if (data.success) { setAiApps(data.data.apps) setTotalPages(data.data.pagination.totalPages) setTotalApps(data.data.pagination.total) setDepartments(data.data.departments || []) // 為每個應用載入統計數據 if (data.data.apps && data.data.apps.length > 0) { const updatedApps = await Promise.all( data.data.apps.map(async (app: any) => { try { const userId = user?.id const statsResponse = await fetch(`/api/apps/${app.id}/interactions${userId ? `?userId=${userId}` : ''}`) if (statsResponse.ok) { const statsData = await statsResponse.json() if (statsData.success) { return { ...app, ...statsData.data } } } } catch (error) { console.error(`載入應用 ${app.name} 統計數據錯誤:`, error) } return app }) ) setAiApps(updatedApps) } } else { console.error('載入應用數據失敗:', data.error) setAiApps([]) } } catch (error) { console.error('載入應用數據錯誤:', error) setAiApps([]) } finally { setIsLoadingApps(false) } } // 載入篩選選項 const loadFilterOptions = async () => { try { const response = await fetch('/api/apps?page=1&limit=1') const data = await response.json() if (data.success) { setDepartments(data.data.departments || []) // 可以添加更多篩選選項的載入 } } catch (error) { console.error('載入篩選選項錯誤:', error) } } // 初始載入 useEffect(() => { loadApps() loadFilterOptions() }, [currentPage, searchTerm, selectedDepartment, selectedType]) // 當前顯示的應用(已經由 API 處理分頁和篩選) const currentApps = aiApps // Reset to first page when filters change const handleFilterChange = (filterType: string, value: string) => { setCurrentPage(1) if (filterType === "department") { setSelectedDepartment(value) } else if (filterType === "type") { setSelectedType(value) } } const handleSearchChange = (value: string) => { setCurrentPage(1) setSearchTerm(value) } const handlePageChange = (page: number) => { setCurrentPage(page) } // 圖標映射函數 const getIconComponent = (iconName: string) => { const iconMap: { [key: string]: any } = { 'Bot': Bot, 'Brain': Brain, 'ImageIcon': ImageIcon, 'Mic': Mic, 'MessageSquare': MessageSquare, 'Settings': Settings, 'Zap': Zap, 'TrendingUp': TrendingUp, 'Star': Star, 'Heart': Heart, 'Eye': Eye, 'Trophy': Trophy, 'Award': Award, 'Medal': Medal, 'Target': Target, 'Users': Users, 'Lightbulb': Lightbulb, 'Search': Search, 'Plus': Plus, 'X': X, 'ChevronLeft': ChevronLeft, 'ChevronRight': ChevronRight, 'ArrowLeft': ArrowLeft, 'Database': Database, 'BarChart3': BarChart3, 'Camera': Camera, 'Smartphone': Smartphone, 'Monitor': Monitor, 'Globe': Globe, 'FileText': FileText, } return iconMap[iconName] || Bot // 預設使用 Bot 圖標 } 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", 音樂生成: "bg-pink-100 text-pink-800 border-pink-200", 程式開發: "bg-indigo-100 text-indigo-800 border-indigo-200", 影像處理: "bg-cyan-100 text-cyan-800 border-cyan-200", 對話系統: "bg-teal-100 text-teal-800 border-teal-200", 數據分析: "bg-yellow-100 text-yellow-800 border-yellow-200", 設計工具: "bg-rose-100 text-rose-800 border-rose-200", 語音技術: "bg-emerald-100 text-emerald-800 border-emerald-200", 教育工具: "bg-violet-100 text-violet-800 border-violet-200", } return colors[type as keyof typeof colors] || "bg-gray-100 text-gray-800 border-gray-200" } const handleOpenAppDetail = (app: any) => { setSelectedApp(app) setShowAppDetail(true) } const handleAppDetailClose = async () => { setShowAppDetail(false) setSelectedApp(null) // 重新載入應用數據以更新統計信息 await loadApps() } const handleSwitchToForgotPassword = () => { setShowLogin(false) setShowForgotPassword(true) } const handleBackToLogin = () => { setShowForgotPassword(false) setShowLogin(true) } const handleTryApp = async (appId: string) => { await incrementViewCount(appId) addToRecentApps(appId) } 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 handleShowCompetitionDetail = (ranking: any, type: "individual" | "team" | "proposal") => { setSelectedRanking(ranking) setSelectedCompetitionType(type) setShowCompetitionDetail(true) } const handleShowAwardDetail = (award: any) => { console.log('🎯 handleShowAwardDetail 被調用:', { award: award ? { id: award.id, competitionId: award.competitionId, awardName: award.awardName, hasCompetitionId: !!award.competitionId } : null }); setSelectedAward(award) setShowAwardDetail(true) } const getFilteredAwards = () => { let filteredAwards = getAwardsByYear(selectedYear) // 搜索功能 - 按应用名称、创作者或奖项名称搜索 if (searchQuery.trim()) { const query = searchQuery.toLowerCase().trim() filteredAwards = filteredAwards.filter((award) => { return ( award.appName?.toLowerCase().includes(query) || award.creator?.toLowerCase().includes(query) || award.awardName?.toLowerCase().includes(query) ) }) } if (selectedCompetitionTypeFilter !== "all") { filteredAwards = filteredAwards.filter((award) => award.competitionType === selectedCompetitionTypeFilter) } if (selectedMonthFilter !== "all") { filteredAwards = filteredAwards.filter((award) => award.month === Number.parseInt(selectedMonthFilter)) } if (selectedAwardCategory !== "all") { if (selectedAwardCategory === "ranking") { filteredAwards = filteredAwards.filter((award) => award.rank > 0 && award.rank <= 3) } else if (selectedAwardCategory === "popular") { filteredAwards = filteredAwards.filter((award) => award.awardType === "popular") } else { filteredAwards = filteredAwards.filter((award) => award.category === selectedAwardCategory) } } return filteredAwards.sort((a, b) => { // Sort by month first, then by rank if (a.month !== b.month) return b.month - a.month if (a.rank !== b.rank) { if (a.rank === 0) return 1 if (b.rank === 0) return -1 return a.rank - b.rank } return 0 }) } const filteredAwards = getFilteredAwards() return (
{/* Header */}
setShowCompetition(false)}>
強茂集團 AI 展示平台

強茂集團 AI 展示平台

PANJIT SEMICONDUCTOR AI SHOWCASE

{/* Competition Link */} {user ? ( <> ) : ( <> )}
{showCompetition ? ( // Competition Content <> {/* Hero Section */}

AI 創新競賽

展示最優秀的 AI 應用作品,見證創新技術的競技與榮耀

競賽排行 得獎作品
{/* Enhanced Filter Section */}
得獎作品展示

展示 {selectedYear} 年度各項競賽的得獎作品

{searchQuery && (
搜尋關鍵字:「{searchQuery}」
)}
{/* Search and Filter Controls */}
{/* Search Bar */}
setSearchQuery(e.target.value)} className="pl-10 pr-10 w-full md:w-96" /> {searchQuery && ( )}
{/* Filter Controls */}
競賽類型:
月份:
獎項類型:
{/* Clear Filters Button */} {(searchQuery || selectedCompetitionTypeFilter !== "all" || selectedMonthFilter !== "all" || selectedAwardCategory !== "all") && (
)}
{/* Statistics */}
{loadingAwards ? '...' : filteredAwards.length}
總獎項數
{loadingAwards ? '...' : filteredAwards.filter((a) => a.rank > 0 && a.rank <= 3).length}
前三名獎項
{loadingAwards ? '...' : filteredAwards.filter((a) => a.awardType === "popular").length}
人氣獎項
{loadingAwards ? '...' : new Set(filteredAwards.map((a) => `${a.year}-${a.month}`)).size}
競賽場次
{/* Awards Grid with Enhanced Display */} {loadingAwards ? (

載入獎項資料中...

) : filteredAwards.length > 0 ? (
{/* Group awards by month */} {Array.from(new Set(filteredAwards.map((award) => award.month))) .sort((a, b) => b - a) .map((month) => { const monthAwards = filteredAwards.filter((award) => award.month === month) const competition = competitions.find((c) => c.month === month && c.year === selectedYear) return (

{selectedYear}年{month}月競賽得獎作品

{competition && ( {getCompetitionTypeIcon(competition.type)} {getCompetitionTypeText(competition.type)} )} {monthAwards.length} 個獎項
{monthAwards.map((award) => ( handleShowAwardDetail(award)} > {/* Rank Badge */} {award.rank > 0 && award.rank <= 3 && (
{award.rank}
)}
{award.icon}
{award.awardName} {getCompetitionTypeIcon(award.competitionType)} {getCompetitionTypeText(award.competitionType)}
{award.appName || award.awardName}

by {award.creator}

{award.year}年{award.month}月
{award.awardType === "popular" ? award.competitionType === "team" ? "人氣指數" : "收藏數" : "評審評分"} {award.awardType === "popular" && award.competitionType === "team" ? `${award.score}` : award.awardType === "popular" ? `${award.score}` : award.score}
))}
) })}
) : (
{searchQuery ? ( ) : ( )}

{searchQuery ? ( <>找不到包含「{searchQuery}」的得獎作品 ) : ( <> {selectedYear}年{selectedMonthFilter !== "all" ? `${selectedMonthFilter}月` : ""} 暫無符合條件的得獎作品 )}

{searchQuery ? "嘗試使用其他關鍵字或調整篩選條件" : "請調整篩選條件查看其他得獎作品"}

{searchQuery && ( )}
)}
{/* Competition Detail Dialog */} {selectedRanking && ( )} {/* Award Detail Dialog */} {selectedAward && ( <> {console.log('🎯 渲染 AwardDetailDialog:', { selectedAward: selectedAward ? { id: selectedAward.id, competitionId: selectedAward.competitionId, awardName: selectedAward.awardName } : null, showAwardDetail })} )} ) : ( // Main Content <> {/* Hero Section */}

探索 AI 的無限可能

發現、體驗和分享最前沿的人工智能應用,讓創新科技為您的工作和生活帶來全新體驗

{/* Search and Filter Section */}
handleSearchChange(e.target.value)} className="pl-10" />
{/* Results summary */}
找到 {totalApps} 個應用,第 {currentPage} 頁,共 {totalPages} 頁
{/* All Apps with Pagination */}

所有應用 ({totalApps}) {isLoadingApps && 載入中...}

{isLoadingApps ? (

載入應用中...

請稍候

) : currentApps.length > 0 ? ( <>
{currentApps.map((app) => { const IconComponent = getIconComponent(app.icon || 'Bot') const likes = Number(app.likesCount) || 0 const views = Number(app.viewsCount) || 0 const rating = Number(app.rating) || 0 const reviewsCount = Number(app.reviewsCount) || 0 return (
{app.name}

by {app.creator}

{app.description}
{app.type} {app.department}
{views}
{rating.toFixed(1)}
{reviewsCount}
) })}
{/* Pagination */} {totalPages > 1 && ( )} ) : (

找不到符合條件的應用

請嘗試調整搜尋條件或篩選器

)}
)} {/* App Detail Dialog */} {selectedApp && } {/* Favorites Dialog */} 我的收藏 您收藏的 AI 應用 {/* App Submission Dialog */} {/* Authentication Dialogs */} { setShowLogin(false) setShowRegister(true) }} onSwitchToForgotPassword={handleSwitchToForgotPassword} />
{/* Footer */}
) }