'use client' import { useState, useEffect } from 'react' import { API_URLS } from '@/lib/config/api' import { Navigation } from '@/components/shared/Navigation' import { useAuth } from '@/contexts/AuthContext' interface UserProfile { id: string email: string displayName: string | null avatarUrl: string | null subscriptionType: string createdAt: string } interface UserSettings { dailyGoal: number reminderTime: string reminderEnabled: boolean difficultyPreference: string autoPlayAudio: boolean showPronunciation: boolean } interface LanguageLevel { value: string label: string description: string examples: string[] } type TabType = 'profile' | 'settings' | 'level' export default function ProfilePage() { const { updateUser } = useAuth() const [activeTab, setActiveTab] = useState('profile') const [profile, setProfile] = useState(null) const [settings, setSettings] = useState(null) const [userLevel, setUserLevel] = useState('A2') const [isLoading, setIsLoading] = useState(true) const [error, setError] = useState(null) const [isSaving, setIsSaving] = useState(false) // 編輯表單狀態 const [editForm, setEditForm] = useState({ displayName: '', dailyGoal: 20, reminderEnabled: true, difficultyPreference: 'balanced', autoPlayAudio: true, showPronunciation: true }) // 英語程度定義 const levels: LanguageLevel[] = [ { value: 'A1', label: 'A1 - 初學者', description: '能理解基本詞彙和簡單句子', examples: ['hello', 'good', 'house', 'eat', 'happy'] }, { value: 'A2', label: 'A2 - 基礎', description: '能處理日常對話和常見主題', examples: ['important', 'difficult', 'interesting', 'beautiful', 'understand'] }, { value: 'B1', label: 'B1 - 中級', description: '能理解清楚標準語言的要點', examples: ['analyze', 'opportunity', 'environment', 'responsibility', 'development'] }, { value: 'B2', label: 'B2 - 中高級', description: '能理解複雜文本的主要內容', examples: ['sophisticated', 'implications', 'comprehensive', 'substantial', 'methodology'] }, { value: 'C1', label: 'C1 - 高級', description: '能流利表達,理解含蓄意思', examples: ['meticulous', 'predominantly', 'intricate', 'corroborate', 'paradigm'] }, { value: 'C2', label: 'C2 - 精通', description: '接近母語水平', examples: ['ubiquitous', 'ephemeral', 'perspicacious', 'multifarious', 'idiosyncratic'] } ] const tabs = [ { id: 'profile' as TabType, label: '個人資料', icon: '👤' }, // { id: 'settings' as TabType, label: '學習設定', icon: '⚙️' }, { id: 'level' as TabType, label: '英語程度', icon: '🎯' } ] // 載入資料 useEffect(() => { loadData() }, []) const loadData = async () => { setIsLoading(true) setError(null) try { const token = localStorage.getItem('auth_token') if (!token) { setError('請先登入') return } console.log('🚀 載入個人檔案資料...') // 並行載入所有資料 const [profileResponse, settingsResponse] = await Promise.all([ fetch(API_URLS.auth('/profile'), { headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${token}` } }), fetch(API_URLS.auth('/settings'), { headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${token}` } }) ]) if (!profileResponse.ok || !settingsResponse.ok) { if (profileResponse.status === 401 || settingsResponse.status === 401) { localStorage.removeItem('auth_token') setError('登入已過期,請重新登入') } else { setError('載入個人資料失敗') } return } const [profileData, settingsData] = await Promise.all([ profileResponse.json(), settingsResponse.json() ]) if (profileData.success && settingsData.success) { setProfile(profileData.data) setSettings(settingsData.data) // 初始化編輯表單 setEditForm({ displayName: profileData.data.displayName || '', dailyGoal: settingsData.data.dailyGoal || 20, reminderEnabled: settingsData.data.reminderEnabled ?? true, difficultyPreference: settingsData.data.difficultyPreference || 'balanced', autoPlayAudio: settingsData.data.autoPlayAudio ?? true, showPronunciation: settingsData.data.showPronunciation ?? true }) console.log('✅ 個人檔案資料載入成功') } else { setError('載入資料失敗') } // 載入英語程度 const savedLevel = localStorage.getItem('userEnglishLevel') if (savedLevel) { setUserLevel(savedLevel) } } catch (error) { console.error('載入個人資料錯誤:', error) setError(error instanceof Error ? error.message : '載入失敗') } finally { setIsLoading(false) } } const handleSaveProfile = async () => { if (!profile) return setIsSaving(true) try { const token = localStorage.getItem('auth_token') if (!token) { setError('請先登入') return } const response = await fetch(API_URLS.auth('/profile'), { method: 'PUT', headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${token}` }, body: JSON.stringify({ displayName: editForm.displayName }) }) if (response.ok) { await loadData() // 重新載入資料 // 同步更新全域 AuthContext 中的用戶資料 updateUser({ displayName: editForm.displayName }) console.log('✅ 個人資料更新成功') } else { setError('儲存失敗') } } catch (error) { setError('儲存失敗') } finally { setIsSaving(false) } } const handleSaveSettings = async () => { setIsSaving(true) try { const token = localStorage.getItem('auth_token') if (!token) { setError('請先登入') return } const response = await fetch(API_URLS.auth('/settings'), { method: 'PUT', headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${token}` }, body: JSON.stringify({ dailyGoal: editForm.dailyGoal, reminderEnabled: editForm.reminderEnabled, difficultyPreference: editForm.difficultyPreference, autoPlayAudio: editForm.autoPlayAudio, showPronunciation: editForm.showPronunciation }) }) if (response.ok) { await loadData() // 重新載入資料 console.log('✅ 學習設定更新成功') } else { setError('儲存失敗') } } catch (error) { setError('儲存失敗') } finally { setIsSaving(false) } } const handleSaveLevel = () => { localStorage.setItem('userEnglishLevel', userLevel) console.log('✅ 英語程度已保存:', userLevel) } const handleLogout = () => { localStorage.removeItem('auth_token') localStorage.removeItem('userEnglishLevel') window.location.href = '/login' } // 載入狀態 if (isLoading) { return (

載入個人資料中...

) } // 錯誤狀態 if (error) { const isAuthError = error.includes('登入') || error.includes('認證') return (
{isAuthError ? '🔒' : '⚠️'}

{isAuthError ? '需要重新登入' : '載入失敗'}

{error}

{isAuthError ? ( ) : ( )}
) } if (!profile || !settings) { return null } return (
{/* 頁面標題 */}

個人檔案

管理您的帳戶資訊和學習偏好設定

{/* 分頁導航 */}
{/* 分頁內容 */}
{/* 個人資料分頁 */} {activeTab === 'profile' && (
{/* 用戶資訊卡片 */}
{profile.avatarUrl ? ( 用戶頭像 ) : ( {(profile.displayName || profile.email)[0].toUpperCase()} )}

{profile.displayName || '用戶'}

{profile.email}

{profile.subscriptionType === 'premium' ? '🌟 Premium' : '🆓 免費版'}
{/* 編輯資料 */}
setEditForm(prev => ({ ...prev, displayName: e.target.value }))} className="flex-1 px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500" placeholder="請輸入顯示名稱" />
{/* 帳戶資訊 */}

帳戶資訊

用戶 ID

{profile.id}

加入時間

{new Date(profile.createdAt).toLocaleDateString('zh-TW')}

{/* 登出 */}
)} {/* 學習設定分頁 */} {activeTab === 'settings' && (
{/* 每日目標 */}
{editForm.dailyGoal} 張詞卡/天
setEditForm(prev => ({ ...prev, dailyGoal: Number(e.target.value) }))} className="w-full h-2 bg-gray-200 rounded-lg appearance-none cursor-pointer slider" />
1 50 100
{/* 學習偏好 */}
{[ { value: 'conservative', label: '保守', desc: '較簡單', color: 'green' }, { value: 'balanced', label: '均衡', desc: '適中', color: 'blue' }, { value: 'aggressive', label: '積極', desc: '較難', color: 'purple' } ].map(option => ( ))}
{/* 音頻和顯示設定 */}

音頻和顯示設定

{[ { key: 'reminderEnabled' as keyof typeof editForm, label: '複習提醒', desc: '接收學習提醒通知' }, { key: 'autoPlayAudio' as keyof typeof editForm, label: '自動播放音頻', desc: '顯示詞卡時自動播放發音' }, { key: 'showPronunciation' as keyof typeof editForm, label: '顯示發音標示', desc: '在詞卡上顯示音標' } ].map(setting => (
{setting.label}

{setting.desc}

))}
{/* 儲存按鈕 */}
)} {/* 英語程度分頁 */} {activeTab === 'level' && (

🎯 英語程度設定

選擇您的英語程度,系統將為您提供個人化的詞彙學習建議

{/* 程度選擇 */}
{levels.map(level => ( ))}
{/* 學習效果預覽 */}

💡 您的個人化學習效果

重點學習範圍

系統將為您標記比目前程度({userLevel})高1-2級的重點詞彙

學習建議

專注學習具有挑戰性但不會太困難的詞彙,提升學習效率

{/* 儲存按鈕 */}
)}
) }