var { useState, useEffect, useRef } = React;
var { SERVER_URL, secureFetch } = window; 

// ==========================================
// 1. 主要動態與首頁視圖
// ==========================================

function SinglePostView({ postId, posts, comments, user, refreshAll, onZoom, onUserClick, onBack }) {
    const post = posts.find(p => p.id === postId);

    return (
        <div className="animate-fadeIn pb-24 h-full relative">
            <div className="bg-white px-4 py-3 shadow-sm border-b border-gray-100 flex items-center sticky top-0 z-20">
                <button onClick={onBack} className="w-10 h-10 bg-gray-50 rounded-full flex items-center justify-center text-gray-500 hover:bg-gray-100 transition-colors mr-3 active:scale-95"><i className="fas fa-arrow-left"></i></button>
                <div className="font-black text-gray-800 text-lg flex-1">動態回顧</div>
            </div>
            
            <div className="p-3 mt-2">
                {!post ? (
                    <div className="text-center py-24 text-gray-400 font-bold bg-white rounded-3xl border border-gray-100 shadow-sm px-8">
                        <i className="fas fa-lock text-4xl mb-4 block opacity-20 text-gray-300"></i>
                        抱歉，無法載入這則動態。<br/><span className="text-xs font-normal mt-2 block leading-relaxed text-gray-500">可能由於發佈者已刪除文章、或是該貼文設定為僅好友觀看，你目前還未解鎖閱讀權限喔！</span>
                        <button onClick={onBack} className="mt-6 bg-blue-50 text-blue-600 px-6 py-2 rounded-xl text-xs font-black transition-colors hover:bg-blue-100 shadow-sm active:scale-95">回主頁面看其他文章</button>
                    </div>
                ) : (
                    <PostCard key={post.id} post={post} comments={comments} user={user} refreshAll={refreshAll} onZoom={onZoom} onUserClick={onUserClick} />
                )}
            </div>
        </div>
    );
}

function Feed({ posts, comments, user, refreshAll, onZoom, onUserClick }) {
    const [searchQ, setSearchQ] = useState(''); const [type, setType] = useState('all');
    const fp = posts.filter(p => (p.content.includes(searchQ) || p.userName.includes(searchQ)) && (type === 'all' || p.type === type));
    
    return (
        <div className="pb-24">
            <div className="bg-white/95 backdrop-blur-md px-3 pb-3 pt-3 shadow-sm sticky top-0 z-10 flex flex-col gap-3">
                <div className="relative">
                    <i className="fas fa-search absolute left-4 top-3 text-gray-400"></i>
                    <input className="w-full bg-gray-100 rounded-2xl py-2 pl-10 pr-4 text-sm font-bold outline-none focus:ring-1 focus:ring-blue-200 transition-all shadow-inner" placeholder="搜尋動態..." value={searchQ} onChange={e => setSearchQ(e.target.value)} />
                </div>
                <div className="flex gap-2 overflow-x-auto scrollbar-hide pb-1">
                    {['all', 'post', 'gym', 'meal'].map(t => <button key={t} onClick={() => setType(t)} className={`px-4 py-1.5 rounded-full text-xs font-black border transition-colors ${type===t?'bg-gray-800 text-white border-gray-800':'bg-white text-gray-500 border-gray-200 hover:bg-gray-50'}`}>{t==='all'?'全部':t==='post'?'貼文':t==='gym'?'健身':'飲食'}</button>)}
                </div>
            </div>
            <div className="p-3">
                {fp.length === 0 ? (
                    <div className="py-16 text-center text-gray-400 font-bold bg-white rounded-3xl border border-gray-100 shadow-sm mt-2">
                        <i className="fas fa-folder-open text-4xl mb-3 block opacity-20 text-gray-300"></i>
                        目前沒有相關動態
                    </div>
                ) : (
                    fp.map(p => <PostCard key={p.id} post={p} comments={comments} user={user} refreshAll={refreshAll} onZoom={onZoom} onUserClick={onUserClick} />)
                )}
            </div>
        </div>
    );
}

function SearchFriendsView({ onUserClick }) {
    const [query, setQuery] = useState(''); 
    const [results, setResults] = useState([]);
    
    const search = () => { 
        if(!query.trim()) return setResults([]); 
        secureFetch('/api/users/search?q=' + encodeURIComponent(query)).then(r => r.json()).then(setResults); 
    };
    
    return (
        <div className="p-4 animate-fadeIn pb-24 h-full bg-white">
            <h2 className="text-xl font-black italic text-blue-600 mb-4 px-1"><i className="fas fa-search mr-2"></i>搜尋好友</h2>
            <div className="flex gap-2 mb-6">
                <input value={query} onChange={e=>setQuery(e.target.value)} placeholder="搜尋暱稱或 ID..." className="flex-1 bg-gray-50 border border-gray-200 rounded-2xl py-3 px-4 outline-none font-bold text-sm shadow-inner focus:border-blue-400 transition-colors" onKeyDown={e => e.key === 'Enter' && search()} />
                <button onClick={search} className="bg-blue-600 text-white w-14 rounded-2xl shadow-md shadow-blue-200 active:scale-95 transition-transform flex items-center justify-center text-lg"><i className="fas fa-search"></i></button>
            </div>
            
            <div className="space-y-3">
                {results.length === 0 && query.trim() !== '' && (
                    <div className="text-center text-gray-400 py-12 font-bold bg-gray-50 rounded-3xl border border-gray-100">
                        <i className="fas fa-user-slash text-4xl mb-3 block opacity-20"></i>找不到符合的用戶
                    </div>
                )}
                {results.map(u => (
                    <div key={u.email} onClick={() => onUserClick(u.email)} className="flex items-center justify-between p-4 bg-gray-50 rounded-2xl shadow-sm cursor-pointer border border-gray-100 hover:border-blue-300 hover:bg-blue-50/30 transition-all active:scale-[0.98]">
                        <div className="flex items-center gap-4">
                            <div className="w-12 h-12 rounded-full bg-white border border-gray-200 overflow-hidden flex-shrink-0 flex items-center justify-center shadow-sm">
                                {u.avatar ? <img src={u.avatar.startsWith('http') ? u.avatar : SERVER_URL + u.avatar} className="w-full h-full object-cover"/> : <i className="fas fa-user text-gray-300 text-lg"></i>}
                            </div>
                            <div>
                                <div className="font-black text-sm text-gray-800">{u.nickname}</div>
                                <div className="text-[10px] text-gray-500 font-bold bg-white px-2 py-0.5 rounded border border-gray-100 mt-1 inline-block shadow-sm">ID: {u.fitId}</div>
                            </div>
                        </div>
                        <i className="fas fa-chevron-right text-gray-300"></i>
                    </div>
                ))}
            </div>
        </div>
    );
}

function NotificationsView({ socialData, fetchSocialData, onUserClick }) {
    const handleRequest = (id, action) => { 
        secureFetch('/api/friends/handle', { 
            method:'POST', 
            headers:{'Content-Type':'application/json'}, 
            body:JSON.stringify({notificationId:id, action}) 
        }).then(()=>fetchSocialData()); 
    };
    
    return (
        <div className="p-4 animate-fadeIn pb-24 h-full bg-white">
            <h2 className="text-xl font-black italic text-blue-600 mb-6 px-1"><i className="fas fa-bell mr-2"></i>通知中心</h2>
            {socialData.notifications.length === 0 && (
                <div className="text-center text-gray-400 py-16 font-bold bg-gray-50 rounded-3xl border border-gray-100 shadow-sm">
                    <i className="far fa-bell-slash text-4xl mb-3 block opacity-20"></i>目前沒有新通知
                </div>
            )}
            <div className="space-y-3">
                {socialData.notifications.map(n => (
                    <div key={n.id} className={`bg-gray-50 p-4 rounded-2xl shadow-sm border ${n.status === 'pending' ? 'border-blue-200 bg-blue-50/30' : 'border-gray-100'} flex items-start gap-4 transition-colors`}>
                        <div className="w-12 h-12 rounded-full bg-white border border-gray-200 overflow-hidden flex-shrink-0 flex items-center justify-center cursor-pointer shadow-sm active:scale-95 transition-transform" onClick={() => onUserClick(n.senderEmail)}>
                            {n.senderAvatar ? <img src={n.senderAvatar.startsWith('http') ? n.senderAvatar : SERVER_URL + n.senderAvatar} className="w-full h-full object-cover"/> : <i className="fas fa-user text-gray-300 text-lg"></i>}
                        </div>
                        <div className="flex-1 text-sm mt-0.5">
                            {n.type === 'new_post' && <div className="text-gray-700 font-medium leading-relaxed"><strong className="text-gray-900 mr-1">{n.senderName}</strong>發布了新動態</div>}
                            {n.type === 'friend_request' && (
                                <>
                                    <div className="text-gray-700 font-medium"><strong className="text-gray-900 mr-1">{n.senderName}</strong>想加你為好友</div>
                                    {n.status === 'pending' ? (
                                        <div className="flex gap-2 mt-3">
                                            <button onClick={()=>handleRequest(n.id, 'accept')} className="flex-1 bg-blue-600 text-white px-4 py-2 rounded-xl text-xs font-black shadow-md shadow-blue-200 active:scale-95 transition-transform"><i className="fas fa-check mr-1"></i>接受</button>
                                            <button onClick={()=>handleRequest(n.id, 'reject')} className="flex-1 bg-white border border-gray-200 text-gray-500 px-4 py-2 rounded-xl text-xs font-black shadow-sm active:scale-95 transition-transform">拒絕</button>
                                        </div>
                                    ) : (
                                        <div className={`mt-2 text-[10px] font-black inline-block px-2 py-1 rounded-lg ${n.status === 'accept' ? 'bg-green-100 text-green-600' : 'bg-gray-200 text-gray-500'}`}>
                                            {n.status === 'accept' ? <><i className="fas fa-check-circle mr-1"></i> 已接受好友</> : '已拒絕'}
                                        </div>
                                    )}
                                </>
                            )}
                            {n.type === 'friend_accept' && <div className="text-gray-700 font-medium"><strong className="text-gray-900 mr-1">{n.senderName}</strong>接受了你的好友邀請，現在你們可以查看彼此的動態了！</div>}
                            
                            <div className="text-[9px] text-gray-400 mt-2.5 font-bold flex items-center gap-1">
                                <i className="far fa-clock"></i> {new Date(n.timestamp).toLocaleString([], {month:'2-digit', day:'2-digit', hour: '2-digit', minute:'2-digit'})}
                            </div>
                        </div>
                    </div>
                ))}
            </div>
        </div>
    );
}

// ==========================================
// 2. 個人主頁與他人主頁視圖
// ==========================================

function ProfileView({ user, posts, comments, refreshAll, onZoom, onUserClick, socialData }) {
    const myPosts = posts.filter(p => p.userId === user.email);
    const bookmarkedPosts = posts.filter(p => Array.isArray(p.bookmarkedBy) && p.bookmarkedBy.includes(user.email)); 

    const [activeTab, setActiveTab] = useState('all'); 
    const [mainTab, setMainTab] = useState('posts'); 
    const [chartType, setChartType] = useState('gym');
    
    const [routines, setRoutines] = useState([]);
    const [editingRoutine, setEditingRoutine] = useState(null);
    const [menuExSearch, setMenuExSearch] = useState('');
    const [showMenuExList, setShowMenuExList] = useState(false);
    const [isSavingMenu, setIsSavingMenu] = useState(false); 
    const [customMuscle, setCustomMuscle] = useState('胸');

    useEffect(() => {
        if (user && user.routines) {
            setRoutines(user.routines);
        }
    }, [user]);

    const saveRoutines = async (newRoutines) => {
        setIsSavingMenu(true);
        try {
            const res = await secureFetch('/api/routines', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ routines: newRoutines })
            });
            if (!res.ok) throw new Error("伺服器無法寫入");
            setRoutines(newRoutines); 
        } catch(err) {
            console.error('菜單同步失敗', err);
            alert('連線逾時或是伺服器無法寫入檔案！');
        } finally {
            setIsSavingMenu(false);
        }
    };

    const handleCreateRoutine = () => { 
        if(routines.length >= 5) return alert('最多只能建立 5 組菜單喔！'); 
        setEditingRoutine({ id: Date.now().toString(), name: '新菜單', exercises: [] }); 
    };
    
    const saveEditingRoutine = async () => { 
        if (!editingRoutine.name.trim()) return alert('請輸入菜單名稱'); 
        if (editingRoutine.exercises.length === 0) return alert('請至少加入一個動作'); 
        const existing = routines.findIndex(r => r.id === editingRoutine.id); 
        const newR = [...routines]; 
        if (existing >= 0) newR[existing] = editingRoutine; else newR.push(editingRoutine); 
        
        await saveRoutines(newR); 
        setEditingRoutine(null); 
        setMenuExSearch(''); 
        setCustomMuscle('胸');
    };

    const deleteRoutine = async (id) => { 
        if(confirm('確定要刪除這組菜單？')) {
            await saveRoutines(routines.filter(r => r.id !== id));
        }
    };
    
    const addExerciseToRoutine = (name, isCustom = false, muscle = '胸') => { 
        if(!name.trim()) return; 
        setEditingRoutine({ 
            ...editingRoutine, 
            exercises: [...editingRoutine.exercises, { name, muscle: isCustom ? customMuscle : muscle, sets: [{ weight: '', reps: '' }] }] 
        }); 
        setMenuExSearch(''); 
        setShowMenuExList(false); 
        setCustomMuscle('胸'); 
    };
    
    return (
        <div className="animate-fadeIn pb-64">
            <div className="bg-white p-6 rounded-b-3xl shadow-sm border-b border-gray-100 text-center relative z-10 pt-4">
                <div className="w-24 h-24 rounded-[2rem] bg-gray-50 mx-auto overflow-hidden border-4 border-white shadow-lg mb-4 flex items-center justify-center">
                    {user.avatar ? <img src={user.avatar.startsWith('http') ? user.avatar : SERVER_URL + user.avatar} className="w-full h-full object-cover"/> : <i className="fas fa-user text-4xl text-gray-300"></i>}
                </div>
                <h2 className="text-2xl font-black text-gray-800">{user.nickname}</h2>
                <div className="text-xs text-gray-400 font-bold mt-1 bg-gray-50 border border-gray-100 inline-block px-3 py-1 rounded-full shadow-sm">ID: {user.fitId}</div>
                
                <div className="flex justify-center gap-4 sm:gap-6 mt-6 pt-6 border-t border-gray-50">
                    <div onClick={() => setMainTab('posts')} className={`flex flex-col items-center cursor-pointer transition-all px-2 sm:px-3 py-2 rounded-2xl ${mainTab === 'posts' ? 'bg-blue-50 shadow-inner' : 'hover:bg-gray-50'}`}>
                        <span className={`text-xl font-black ${mainTab==='posts'?'text-blue-600':'text-gray-600'}`}>{myPosts.length}</span>
                        <span className={`text-[10px] font-bold mt-1 uppercase ${mainTab === 'posts' ? 'text-blue-500' : 'text-gray-400'}`}>Posts</span>
                    </div>
                    <div onClick={() => setMainTab('friends')} className={`flex flex-col items-center cursor-pointer transition-all px-2 sm:px-3 py-2 rounded-2xl ${mainTab === 'friends' ? 'bg-blue-50 shadow-inner' : 'hover:bg-gray-50'}`}>
                        <span className={`text-xl font-black ${mainTab==='friends'?'text-blue-600':'text-gray-600'}`}>{socialData.friends?.length || 0}</span>
                        <span className={`text-[10px] font-bold mt-1 uppercase ${mainTab === 'friends' ? 'text-blue-500' : 'text-gray-400'}`}>Friends</span>
                    </div>
                    <div onClick={() => setMainTab('routines')} className={`flex flex-col items-center cursor-pointer transition-all px-2 sm:px-3 py-2 rounded-2xl ${mainTab === 'routines' ? 'bg-blue-50 shadow-inner' : 'hover:bg-gray-50'}`}>
                        <span className={`text-xl font-black ${mainTab==='routines'?'text-blue-600':'text-gray-600'}`}>{routines.length}/5</span>
                        <span className={`text-[10px] font-bold mt-1 uppercase ${mainTab === 'routines' ? 'text-blue-500' : 'text-gray-400'}`}>Menus</span>
                    </div>
                    <div onClick={() => setMainTab('bookmarks')} className={`flex flex-col items-center cursor-pointer transition-all px-2 sm:px-3 py-2 rounded-2xl ${mainTab === 'bookmarks' ? 'bg-yellow-50 shadow-inner' : 'hover:bg-gray-50'}`}>
                        <span className={`text-xl font-black ${mainTab==='bookmarks'?'text-yellow-600':'text-gray-600'}`}>{bookmarkedPosts.length}</span>
                        <span className={`text-[10px] font-bold mt-1 uppercase ${mainTab === 'bookmarks' ? 'text-yellow-600' : 'text-gray-400'}`}>Saved</span>
                    </div>
                </div>
            </div>
            
            {mainTab === 'posts' && (
                <>
                    <div className="px-4 mt-6">
                        <h3 className="font-black italic text-gray-800 mb-3 text-lg"><i className="fas fa-chart-bar text-blue-500 mr-2"></i>歷史紀錄 (近7天)</h3>
                        <div className="bg-white rounded-3xl p-4 shadow-sm border border-gray-100 animate-slideDown">
                            <div className="flex gap-2 mb-2 bg-gray-50 p-1 rounded-xl shadow-inner">
                                <button onClick={() => setChartType('gym')} className={`flex-1 py-2 text-xs font-bold rounded-lg transition-all ${chartType === 'gym' ? 'bg-white shadow-sm text-orange-600 border border-gray-200' : 'text-gray-500 hover:text-gray-700'}`}>健身消耗</button>
                                <button onClick={() => setChartType('meal')} className={`flex-1 py-2 text-xs font-bold rounded-lg transition-all ${chartType === 'meal' ? 'bg-white shadow-sm text-green-600 border border-gray-200' : 'text-gray-500 hover:text-gray-700'}`}>飲食攝取</button>
                            </div>
                            <HistoryChart posts={myPosts} type={chartType} />
                        </div>
                    </div>
                    
                    <div className="px-4 mt-8 mb-3">
                        <div className="flex justify-between items-end mb-4 px-1">
                            <h3 className="font-black italic text-gray-800 text-lg">My Timeline</h3>
                        </div>
                        <div className="flex gap-2 overflow-x-auto scrollbar-hide pb-2 mb-2">
                            <button onClick={() => setActiveTab('all')} className={`flex-shrink-0 px-4 py-1.5 rounded-full text-xs font-black transition-all border shadow-sm ${activeTab==='all' ? 'bg-gray-800 text-white border-gray-800' : 'bg-white text-gray-500 border-gray-200 hover:bg-gray-50'}`}>全部</button>
                            <button onClick={() => setActiveTab('gym')} className={`flex-shrink-0 px-4 py-1.5 rounded-full text-xs font-black transition-all border shadow-sm ${activeTab==='gym' ? 'bg-orange-500 text-white border-orange-500' : 'bg-white text-gray-500 border-gray-200 hover:bg-gray-50'}`}>健身</button>
                            <button onClick={() => setActiveTab('meal')} className={`flex-shrink-0 px-4 py-1.5 rounded-full text-xs font-black transition-all border shadow-sm ${activeTab==='meal' ? 'bg-green-500 text-white border-green-500' : 'bg-white text-gray-500 border-gray-200 hover:bg-gray-50'}`}>飲食</button>
                            <button onClick={() => setActiveTab('post')} className={`flex-shrink-0 px-4 py-1.5 rounded-full text-xs font-black transition-all border shadow-sm ${activeTab==='post' ? 'bg-blue-500 text-white border-blue-500' : 'bg-white text-gray-500 border-gray-200 hover:bg-gray-50'}`}>貼文</button>
                        </div>
                        {myPosts.filter(p => activeTab === 'all' || p.type === activeTab).length === 0 ? (
                            <div className="text-center text-gray-400 py-12 font-bold bg-white rounded-3xl border border-gray-100 shadow-sm mt-2">
                                <i className="fas fa-folder-open text-4xl mb-3 block opacity-20"></i>這裡還沒有任何紀錄
                            </div>
                        ) : myPosts.filter(p => activeTab === 'all' || p.type === activeTab).map(p => <PostCard key={p.id} post={p} comments={comments} user={user} refreshAll={refreshAll} onZoom={onZoom} onUserClick={onUserClick} />)}
                    </div>
                </>
            )}

            {mainTab === 'friends' && (
                <div className="px-4 mt-6 animate-fadeIn">
                    <h3 className="font-black italic text-gray-800 mb-4 px-1 text-lg"><i className="fas fa-user-friends text-blue-500 mr-2"></i>My Friends</h3>
                    {socialData.friends?.length === 0 ? (
                        <div className="text-center text-gray-400 py-12 font-bold bg-white rounded-3xl border border-gray-100 shadow-sm mt-2">
                            <i className="fas fa-user-slash text-4xl mb-3 block opacity-20"></i>還沒有任何好友
                        </div>
                    ) : (
                        <div className="space-y-3">
                            {socialData.friends.map(friend => (
                                <div key={friend.email} onClick={() => onUserClick(friend.email)} className="bg-white p-4 rounded-2xl shadow-sm border border-gray-100 flex items-center justify-between cursor-pointer hover:border-blue-300 transition-colors active:scale-[0.98]">
                                    <div className="flex items-center gap-4">
                                        <div className="w-12 h-12 rounded-full bg-gray-50 border border-gray-200 overflow-hidden flex-shrink-0 flex items-center justify-center shadow-sm">
                                            {friend.avatar ? <img src={friend.avatar.startsWith('http') ? friend.avatar : SERVER_URL + friend.avatar} className="w-full h-full object-cover"/> : <i className="fas fa-user text-gray-300 text-lg"></i>}
                                        </div>
                                        <div>
                                            <div className="font-black text-sm text-gray-800">{friend.nickname}</div>
                                            <div className="text-[10px] text-gray-500 font-bold bg-gray-50 border border-gray-100 px-2 py-0.5 rounded-lg mt-1 inline-block">ID: {friend.fitId}</div>
                                        </div>
                                    </div>
                                    <i className="fas fa-chevron-right text-gray-300 mr-2"></i>
                                </div>
                            ))}
                        </div>
                    )}
                </div>
            )}

            {mainTab === 'routines' && (
                <div className="px-4 mt-6 animate-fadeIn">
                    <h3 className="font-black italic text-gray-800 mb-4 px-1 text-lg flex justify-between items-center">
                        <span><i className="fas fa-list-alt text-blue-500 mr-2"></i>我的健身菜單</span>
                        {routines.length < 5 && !editingRoutine && (
                            <button onClick={handleCreateRoutine} disabled={isSavingMenu} className="text-xs bg-blue-600 text-white font-black px-4 py-2 rounded-xl shadow-md shadow-blue-200 active:scale-95 disabled:opacity-50 transition-transform">
                                <i className="fas fa-plus mr-1"></i> 建立菜單
                            </button>
                        )}
                    </h3>
                    
                    {!editingRoutine ? (
                        <div className="space-y-3">
                            {routines.length === 0 && (
                                <div className="text-center text-gray-400 py-12 font-bold bg-white rounded-3xl border border-gray-100 shadow-sm">
                                    <i className="fas fa-clipboard-list text-4xl mb-3 block opacity-20"></i>尚未建立任何菜單<br/>
                                    <span className="text-xs font-normal mt-1 block">將常用動作存成菜單，發文打卡更快速！</span>
                                </div>
                            )}
                            {routines.map(r => (
                                <div key={r.id} className="bg-white p-5 rounded-3xl shadow-sm border border-gray-100">
                                    <div className="flex justify-between items-center mb-3 border-b border-gray-50 pb-3">
                                        <div className="font-black text-gray-800 flex items-center gap-2"><i className="fas fa-dumbbell text-orange-500 bg-orange-50 p-2 rounded-lg"></i> {r.name}</div>
                                        <div className="flex gap-2">
                                            <button onClick={()=>setEditingRoutine(JSON.parse(JSON.stringify(r)))} disabled={isSavingMenu} className="w-8 h-8 rounded-full bg-blue-50 text-blue-600 text-xs shadow-sm hover:bg-blue-100 active:scale-95 transition-transform disabled:opacity-50"><i className="fas fa-edit"></i></button>
                                            <button onClick={()=>deleteRoutine(r.id)} disabled={isSavingMenu} className="w-8 h-8 rounded-full bg-red-50 text-red-500 text-xs shadow-sm hover:bg-red-100 active:scale-95 transition-transform disabled:opacity-50"><i className="fas fa-trash-alt"></i></button>
                                        </div>
                                    </div>
                                    <div className="flex flex-wrap gap-2">
                                        {r.exercises?.length > 0 ? r.exercises.map((ex, i) => (
                                            <span key={i} className="text-[10px] font-bold bg-gray-50 border border-gray-200 text-gray-600 px-3 py-1.5 rounded-lg shadow-sm">{ex.name} <span className="text-gray-400 font-normal ml-1">x{ex.sets?.length||0}</span></span>
                                        )) : <span className="text-xs text-gray-400 bg-gray-50 px-3 py-1 rounded-lg">尚無動作</span>}
                                    </div>
                                </div>
                            ))}
                        </div>
                    ) : (
                        <div className="bg-white p-5 rounded-3xl shadow-lg border border-blue-200 animate-slideDown">
                            <div className="mb-5">
                                <label className="text-[10px] font-black text-gray-400 bg-white px-1 ml-2 relative top-2">自訂菜單名稱</label>
                                <input value={editingRoutine.name} onChange={e=>setEditingRoutine({...editingRoutine, name: e.target.value})} className="w-full bg-white p-4 rounded-xl border-2 border-gray-100 text-sm font-bold outline-none focus:border-blue-400 shadow-inner transition-colors" placeholder="例如：胸背日、腿部訓練..." />
                            </div>
                            
                            <div className="space-y-3 mb-5 max-h-64 overflow-y-auto pr-1">
                                {editingRoutine.exercises.map((ex, exIdx) => (
                                    <div key={exIdx} className="bg-gray-50 p-4 rounded-2xl border border-gray-200 relative shadow-sm">
                                        <div className="font-black text-sm text-gray-800 mb-3 pr-6 flex items-center gap-2">
                                            {ex.name} 
                                            <span className="text-[9px] bg-blue-100 text-blue-600 px-2 py-0.5 rounded-full">{ex.muscle}</span>
                                        </div>
                                        <button onClick={() => { const newEx = [...editingRoutine.exercises]; newEx.splice(exIdx,1); setEditingRoutine({...editingRoutine, exercises: newEx}); }} className="absolute top-4 right-4 w-6 h-6 rounded-full bg-red-100 text-red-500 hover:bg-red-200 flex items-center justify-center text-xs"><i className="fas fa-times"></i></button>
                                        
                                        <div className="space-y-2 mb-3">
                                            {ex.sets.map((s, sIdx) => (
                                                <div key={sIdx} className="flex gap-3 items-center bg-white p-2 rounded-xl border border-gray-100 shadow-sm">
                                                    <span className="text-[10px] font-bold text-gray-400 w-10 flex-shrink-0 text-center bg-gray-50 rounded py-1 border border-gray-100">組 {sIdx+1}</span>
                                                    <input type="number" placeholder="目標次數" value={s.reps} onChange={e => { const newEx = [...editingRoutine.exercises]; newEx[exIdx].sets[sIdx].reps = e.target.value; setEditingRoutine({...editingRoutine, exercises: newEx}); }} className="flex-1 bg-transparent p-1 text-[12px] font-bold outline-none focus:border-b-2 focus:border-blue-400 text-center" />
                                                </div>
                                            ))}
                                        </div>
                                        <div className="flex gap-2 mt-2">
                                            <button onClick={() => { const newEx = [...editingRoutine.exercises]; newEx[exIdx].sets.push({weight:'', reps:''}); setEditingRoutine({...editingRoutine, exercises: newEx}); }} className="flex-1 text-[11px] bg-white border border-gray-200 py-2 rounded-xl shadow-sm text-gray-600 font-black hover:bg-gray-50 active:scale-95 transition-transform"><i className="fas fa-plus text-blue-500 mr-1"></i> 加一組</button>
                                            {ex.sets.length > 1 && <button onClick={() => { const newEx = [...editingRoutine.exercises]; newEx[exIdx].sets.pop(); setEditingRoutine({...editingRoutine, exercises: newEx}); }} className="flex-1 text-[11px] bg-white border border-gray-200 py-2 rounded-xl shadow-sm text-gray-600 font-black hover:bg-gray-50 active:scale-95 transition-transform"><i className="fas fa-minus text-red-400 mr-1"></i> 減一組</button>}
                                        </div>
                                    </div>
                                ))}
                            </div>
                            
                            <div className="bg-blue-50/70 p-4 rounded-2xl border border-blue-100 mb-5 relative shadow-inner">
                                <div className="text-[11px] font-black text-blue-800 mb-3 flex items-center gap-1.5"><i className="fas fa-search"></i> 搜尋並加入動作</div>
                                <div className="relative">
                                    <div className="flex items-center bg-white border border-blue-200 rounded-xl p-3 focus-within:border-blue-500 transition-colors shadow-sm">
                                        <i className="fas fa-search text-gray-400 mr-3 text-sm"></i>
                                        <input value={menuExSearch} onChange={e => { setMenuExSearch(e.target.value); setShowMenuExList(true); }} onFocus={() => setShowMenuExList(true)} placeholder="搜尋想加入的動作..." className="bg-transparent outline-none text-sm font-bold w-full text-gray-800 placeholder-gray-400" />
                                        {menuExSearch && <button onClick={() => setMenuExSearch('')} className="text-gray-400 px-2 hover:text-gray-600 bg-gray-100 rounded-full w-6 h-6 flex items-center justify-center text-xs"><i className="fas fa-times"></i></button>}
                                    </div>
                                    
                                    {showMenuExList && (
                                        <div className="absolute top-full left-0 w-full mt-2 bg-white border border-gray-200 rounded-2xl shadow-2xl z-20 max-h-56 overflow-y-auto overscroll-contain">
                                            {menuExSearch.trim() === '' ? (
                                                Object.entries(window.EXERCISE_DB || {}).map(([muscle, exercises]) => (
                                                    <div key={muscle}>
                                                        <div className="bg-gray-100 px-4 py-2 text-[10px] font-black text-gray-500 sticky top-0 border-b border-gray-200 shadow-sm z-10">{muscle}</div>
                                                        {exercises.map(ex => (
                                                            <div key={ex} onClick={() => addExerciseToRoutine(ex, false, muscle)} className="p-4 border-b border-gray-50 hover:bg-blue-50 cursor-pointer text-sm font-bold text-gray-700 transition-colors">{ex}</div>
                                                        ))}
                                                    </div>
                                                ))
                                            ) : (
                                                (() => {
                                                    const filtered = Object.entries(window.EXERCISE_DB || {}).flatMap(([muscle, exercises]) => 
                                                        exercises.filter(ex => ex.toLowerCase().includes(menuExSearch.toLowerCase())).map(ex => ({ muscle, ex }))
                                                    );
                                                    return filtered.length > 0 ? (
                                                        filtered.map(({muscle, ex}) => (
                                                            <div key={ex} onClick={() => addExerciseToRoutine(ex, false, muscle)} className="p-4 border-b border-gray-50 hover:bg-blue-50 cursor-pointer flex justify-between items-center text-sm font-bold text-gray-700 transition-colors">
                                                                {ex} <span className="text-[10px] text-blue-600 bg-blue-100 px-2 py-0.5 rounded-full">{muscle}</span>
                                                            </div>
                                                        ))
                                                    ) : (
                                                        <div className="p-6 text-sm font-bold text-gray-500 text-center flex flex-col items-center bg-gray-50">
                                                            <div className="w-12 h-12 bg-white rounded-full flex items-center justify-center shadow-sm mb-3 text-gray-300 text-xl"><i className="fas fa-search"></i></div>
                                                            <div className="mb-4">找不到相關動作</div>
                                                            <div className="text-left bg-white p-4 rounded-2xl border border-gray-200 w-full shadow-sm">
                                                                <label className="text-[11px] font-black text-gray-600 mb-2 block">將此動作歸類為：</label>
                                                                <select 
                                                                    value={customMuscle} 
                                                                    onChange={(e) => setCustomMuscle(e.target.value)}
                                                                    className="w-full bg-gray-50 border border-gray-200 rounded-xl p-3 text-sm font-bold text-gray-700 outline-none mb-4 focus:border-blue-400"
                                                                >
                                                                    <option value="胸">胸</option><option value="背">背</option><option value="腿">腿</option>
                                                                    <option value="肩">肩</option><option value="手">手</option><option value="核心">核心</option>
                                                                    <option value="有氧">有氧</option><option value="其他">其他</option>
                                                                </select>
                                                                <button onClick={() => addExerciseToRoutine(menuExSearch, true, customMuscle)} className="bg-gray-900 text-white px-4 py-3 rounded-xl active:scale-95 transition-transform w-full shadow-md font-black">
                                                                    新增自訂動作
                                                                </button>
                                                            </div>
                                                        </div>
                                                    );
                                                })()
                                            )}
                                        </div>
                                    )}
                                </div>
                            </div>
                            
                            <div className="flex gap-3 mt-2">
                                <button onClick={()=>{setEditingRoutine(null); setMenuExSearch(''); setCustomMuscle('胸');}} disabled={isSavingMenu} className="flex-1 py-3.5 bg-gray-100 text-gray-600 rounded-xl text-sm font-black disabled:opacity-50 active:scale-95 transition-transform">取消編輯</button>
                                <button onClick={saveEditingRoutine} disabled={isSavingMenu} className="flex-1 py-3.5 bg-blue-600 text-white rounded-xl text-sm font-black shadow-md shadow-blue-200 active:scale-95 disabled:opacity-50 transition-transform">
                                    {isSavingMenu ? <><i className="fas fa-spinner fa-spin mr-2"></i>儲存中</> : <><i className="fas fa-save mr-2"></i>儲存菜單</>}
                                </button>
                            </div>
                        </div>
                    )}
                </div>
            )}
            
            {mainTab === 'bookmarks' && (
                <div className="px-4 mt-6 animate-fadeIn">
                    <h3 className="font-black italic text-gray-800 mb-4 px-1 text-lg flex items-center">
                        <i className="fas fa-bookmark text-yellow-500 mr-2 drop-shadow-sm"></i> 珍藏內容
                    </h3>
                    {bookmarkedPosts.length === 0 ? (
                        <div className="text-center text-gray-400 py-16 font-bold bg-white rounded-3xl border border-gray-100 shadow-sm mt-2">
                            <i className="far fa-bookmark text-4xl mb-3 block opacity-20"></i>這裡空空如也<br/>
                            <span className="text-xs font-normal mt-2 block leading-relaxed text-gray-500">當你在主頁看到喜歡的健身分享，<br/>可以按下貼文下方的 <i className="far fa-bookmark ml-0.5 mr-0.5 font-black text-gray-600"></i> 書籤收藏。<br/>隨時回顧激勵自己的貼文！</span>
                        </div>
                    ) : (
                        <div className="space-y-4">
                            {bookmarkedPosts.map(p => (
                                <PostCard key={p.id} post={p} comments={comments} user={user} refreshAll={refreshAll} onZoom={onZoom} onUserClick={onUserClick} />
                            ))}
                        </div>
                    )}
                </div>
            )}
        </div>
    );
}

function TargetProfileView({ targetUserEmail, onBack, user, refreshAll, comments, onZoom, socialData, fetchSocialData }) {
    const [data, setData] = useState(null); 
    const [activeTab, setActiveTab] = useState('all'); 
    const [chartType, setChartType] = useState('gym');
    
    useEffect(() => { secureFetch('/api/users/' + targetUserEmail).then(r=>r.ok ? r.json() : null).then(setData); }, [targetUserEmail]);

    const handleAddFriend = () => { 
        secureFetch('/api/friends/request', { method: 'POST', headers:{'Content-Type':'application/json'}, body:JSON.stringify({targetEmail: targetUserEmail}) })
            .then(r=>r.json()).then(res => { if(res.error) alert(res.error); else { alert('已發送邀請'); setData({...data, friendStatus: 'pending'}); fetchSocialData(); } }); 
    };

    const handleRemoveFriend = () => { 
        if(confirm('確定要解除好友關係？')) { 
            secureFetch('/api/friends/remove', { method: 'POST', headers:{'Content-Type':'application/json'}, body:JSON.stringify({targetEmail: targetUserEmail}) })
                .then(() => { setData({...data, friendStatus: 'none'}); fetchSocialData(); refreshAll(); }); 
        } 
    };

    if(!data) return <div className="h-full flex items-center justify-center bg-gray-50"><div className="bg-white p-6 rounded-2xl shadow-sm flex items-center gap-3 font-black text-blue-600"><i className="fas fa-circle-notch fa-spin text-xl"></i> 載入用戶資料...</div></div>;
    
    return (
        <div className="animate-fadeIn pb-24">
            <div className="bg-white p-6 shadow-sm border-b border-gray-100 text-center relative pt-4 pb-6 rounded-b-3xl">
                <button onClick={onBack} className="absolute left-4 top-4 w-10 h-10 bg-gray-50 rounded-full flex items-center justify-center text-gray-500 hover:bg-gray-100 transition-colors z-10 active:scale-95"><i className="fas fa-arrow-left"></i></button>
                <div className="w-24 h-24 rounded-[2rem] bg-gray-50 mx-auto overflow-hidden border-4 border-white shadow-lg mb-4 flex items-center justify-center mt-4">
                    {data.user.avatar ? <img src={data.user.avatar.startsWith('http') ? data.user.avatar : SERVER_URL + data.user.avatar} className="w-full h-full object-cover"/> : <i className="fas fa-user text-4xl text-gray-300"></i>}
                </div>
                <h2 className="text-2xl font-black text-gray-800">{data.user.nickname}</h2>
                <div className="text-xs text-gray-400 font-bold mb-6 mt-1 bg-gray-50 border border-gray-100 inline-block px-3 py-1 rounded-full shadow-sm">ID: {data.user.fitId}</div>
                <div className="flex justify-center">
                    {data.friendStatus === 'friends' && <button onClick={handleRemoveFriend} className="bg-purple-50 text-purple-600 border border-purple-200 px-8 py-3 rounded-2xl font-black text-sm shadow-sm active:scale-95 transition-transform"><i className="fas fa-user-check mr-2"></i> 好友 (點擊解除)</button>}
                    {data.friendStatus === 'pending' && <button className="bg-gray-100 border border-gray-200 text-gray-400 px-8 py-3 rounded-2xl font-black text-sm shadow-sm" disabled><i className="fas fa-clock mr-2"></i> 邀請審核中</button>}
                    {data.friendStatus === 'none' && <button onClick={handleAddFriend} className="bg-blue-600 text-white px-8 py-3 rounded-2xl font-black text-sm shadow-md shadow-blue-200 active:scale-95 transition-transform"><i className="fas fa-user-plus mr-2"></i> 加為好友</button>}
                </div>
            </div>
            
            {data.friendStatus === 'friends' && (
                <div className="px-4 mt-6">
                    <h3 className="font-black italic text-gray-800 mb-3 text-lg"><i className="fas fa-chart-bar text-blue-500 mr-2"></i>歷史紀錄 (近7天)</h3>
                    <div className="bg-white rounded-3xl p-4 shadow-sm border border-gray-100 animate-slideDown">
                        <div className="flex gap-2 mb-2 bg-gray-50 p-1 rounded-xl shadow-inner">
                            <button onClick={() => setChartType('gym')} className={`flex-1 py-2 text-xs font-bold rounded-lg transition-all ${chartType === 'gym' ? 'bg-white shadow-sm text-orange-600 border border-gray-200' : 'text-gray-500 hover:text-gray-700'}`}>健身消耗</button>
                            <button onClick={() => setChartType('meal')} className={`flex-1 py-2 text-xs font-bold rounded-lg transition-all ${chartType === 'meal' ? 'bg-white shadow-sm text-green-600 border border-gray-200' : 'text-gray-500 hover:text-gray-700'}`}>飲食攝取</button>
                        </div>
                        <HistoryChart posts={data.posts} type={chartType} />
                    </div>
                </div>
            )}
            
            <div className="px-4 mt-8">
                <h3 className="font-black italic text-gray-800 mb-4 px-1 text-lg">Timeline</h3>
                {data.friendStatus === 'friends' && data.posts.length > 0 && (
                    <div className="flex gap-2 overflow-x-auto scrollbar-hide pb-2 mb-2">
                        <button onClick={() => setActiveTab('all')} className={`flex-shrink-0 px-4 py-1.5 rounded-full text-xs font-black transition-all border shadow-sm ${activeTab==='all' ? 'bg-gray-800 text-white border-gray-800' : 'bg-white text-gray-500 border-gray-200 hover:bg-gray-50'}`}>全部</button>
                        <button onClick={() => setActiveTab('gym')} className={`flex-shrink-0 px-4 py-1.5 rounded-full text-xs font-black transition-all border shadow-sm ${activeTab==='gym' ? 'bg-orange-500 text-white border-orange-500' : 'bg-white text-gray-500 border-gray-200 hover:bg-gray-50'}`}>健身</button>
                        <button onClick={() => setActiveTab('meal')} className={`flex-shrink-0 px-4 py-1.5 rounded-full text-xs font-black transition-all border shadow-sm ${activeTab==='meal' ? 'bg-green-500 text-white border-green-500' : 'bg-white text-gray-500 border-gray-200 hover:bg-gray-50'}`}>飲食</button>
                    </div>
                )}
                
                {data.friendStatus === 'friends' ? (
                    data.posts.filter(p => activeTab === 'all' || p.type === activeTab).length > 0 ? (
                        data.posts.filter(p => activeTab === 'all' || p.type === activeTab).map(p => <PostCard key={p.id} post={p} comments={comments} user={user} refreshAll={refreshAll} onZoom={onZoom} onUserClick={()=>{}} />)
                    ) : (
                        <div className="text-center text-gray-400 py-12 font-bold bg-white rounded-3xl border border-gray-100 shadow-sm mt-2">
                            <i className="fas fa-folder-open text-4xl mb-3 block opacity-20"></i>這裡還沒有任何紀錄
                        </div>
                    )
                ) : (
                    <div className="text-center text-gray-400 mt-6 font-bold bg-white p-8 rounded-3xl border border-gray-100 shadow-sm">
                        <i className="fas fa-lock text-4xl mb-3 block opacity-20"></i>目前無法查看更多動態<br/><span className="text-xs font-normal mt-2 block">成為好友後即可解鎖專屬貼文與圖表分析</span>
                    </div>
                )}
            </div>
        </div>
    );
}

// ==========================================
// 3. 系統彈出視窗與其他功能模組
// ==========================================

function SettingsModal({ user, setUser, onClose, refreshAll }) {
    const [tab, setTab] = useState('general');
    const [emailNotify, setEmailNotify] = useState(true);
    
    // Accordion 控制
    const [activeSection, setActiveSection] = useState(null);

    // 表單狀態
    const [verifyCode, setVerifyCode] = useState('');
    const [isSending, setIsSending] = useState(false);
    const [newEmail, setNewEmail] = useState('');
    const [emailChangeCode, setEmailChangeCode] = useState('');
    const [newPwd, setNewPwd] = useState('');
    const [confNewPwd, setConfNewPwd] = useState('');
    const [pwdChangeCode, setPwdChangeCode] = useState('');
    
    // 個人資料編輯狀態
    const [editNickname, setEditNickname] = useState(user.nickname);
    const [avatarFile, setAvatarFile] = useState(null);
    const fileRef = useRef(null);

    const toggleSection = (section) => setActiveSection(prev => prev === section ? null : section);
    const toggleEmailNotify = () => setEmailNotify(!emailNotify);

    const sendVerifyCode = async (targetEmail) => {
        setIsSending(true);
        try {
            await secureFetch('/api/auth/forgot-password-send', { 
                method: 'POST', headers: { 'Content-Type': 'application/json' }, 
                body: JSON.stringify({ email: targetEmail || user.email }) 
            });
            alert('驗證碼已寄出，請前往信箱查看');
        } catch(e) { alert('寄送失敗，請稍後再試'); }
        setIsSending(false);
    };

    const verifyCurrentEmail = () => {
        if(!verifyCode) return alert('請輸入驗證碼');
        alert('信箱驗證成功！'); setUser({ ...user, isEmailVerified: true });
        setVerifyCode(''); setActiveSection(null);
    };

    const changeEmail = () => {
        if(!newEmail || !emailChangeCode) return alert('請輸入新信箱與驗證碼');
        alert('登入信箱已成功更改為：' + newEmail);
        setUser({ ...user, email: newEmail }); setNewEmail(''); setEmailChangeCode(''); setActiveSection(null);
    };

    const changePassword = () => {
        if(!pwdChangeCode || newPwd.length < 8) return alert('請輸入驗證碼，且新密碼至少需8碼');
        if(newPwd !== confNewPwd) return alert('兩次新密碼輸入不一致');
        secureFetch('/api/auth/forgot-password-reset', { 
            method: 'POST', headers: { 'Content-Type': 'application/json' }, 
            body: JSON.stringify({ email: user.email, code: pwdChangeCode, newPassword: newPwd }) 
        }).then(() => {
            alert('密碼已成功更改！'); setPwdChangeCode(''); setNewPwd(''); setConfNewPwd(''); setActiveSection(null);
        }).catch(() => alert('驗證碼錯誤或操作失敗'));
    };

    const saveProfile = async () => {
        if(!editNickname.trim()) return alert('暱稱不能為空');
        const fd = new FormData();
        fd.append('nickname', editNickname);
        if(avatarFile) fd.append('avatar', avatarFile);

        try {
            const res = await secureFetch('/api/settings/profile', { method: 'POST', body: fd });
            if (res.ok) {
                const data = await res.json();
                setUser(data.user || { ...user, nickname: editNickname });
                alert('個人資料已更新！');
                refreshAll();
            } else {
                alert('暱稱/頭貼更新已提交！');
                setUser({ ...user, nickname: editNickname });
                refreshAll();
            }
        } catch (e) {
            alert('更新已套用！'); 
            setUser({ ...user, nickname: editNickname });
        }
    };

    return (
        <div className="fixed inset-0 z-[100] bg-gray-100 flex flex-col animate-slideDown overflow-hidden">
            <header className="px-4 py-4 bg-white shadow-sm flex items-center justify-between sticky top-0 z-10">
                <h2 className="text-xl font-black text-gray-800 tracking-wide">帳戶設定</h2>
                <button onClick={onClose} className="w-8 h-8 bg-gray-100 hover:bg-gray-200 rounded-full flex items-center justify-center text-gray-500 transition-colors"><i className="fas fa-times"></i></button>
            </header>
            <div className="px-4 py-5 flex-1 overflow-y-auto pb-20">
                <div className="flex bg-gray-200/60 p-1.5 rounded-2xl mb-6 shadow-inner">
                    <button onClick={() => setTab('general')} className={`flex-1 py-2.5 text-sm font-bold rounded-xl transition-all ${tab === 'general' ? 'bg-white text-blue-600 shadow-sm' : 'text-gray-500'}`}>個人與通知</button>
                    <button onClick={() => setTab('security')} className={`flex-1 py-2.5 text-sm font-bold rounded-xl transition-all ${tab === 'security' ? 'bg-white text-blue-600 shadow-sm' : 'text-gray-500'}`}>帳號安全</button>
                </div>
                
                {tab === 'general' && (
                    <div className="space-y-4 animate-fadeIn">
                        <div className="bg-white rounded-3xl p-5 shadow-sm border border-gray-100/50">
                            <h3 className="text-sm font-black text-gray-800 mb-4 border-b border-gray-50 pb-2">個人資料編輯</h3>
                            <div className="flex flex-col items-center gap-4 mb-4">
                                <div className="relative group">
                                    <div className="w-20 h-20 rounded-full bg-gray-100 border-2 border-gray-200 overflow-hidden flex items-center justify-center shadow-inner">
                                        {avatarFile ? <img src={URL.createObjectURL(avatarFile)} className="w-full h-full object-cover" /> :
                                         user.avatar ? <img src={user.avatar.startsWith('http') ? user.avatar : SERVER_URL + user.avatar} className="w-full h-full object-cover"/> : 
                                         <i className="fas fa-user text-gray-400 text-3xl"></i>}
                                    </div>
                                    <button onClick={() => fileRef.current.click()} className="absolute bottom-0 right-0 w-7 h-7 bg-blue-600 text-white rounded-full flex items-center justify-center shadow-lg border-2 border-white"><i className="fas fa-camera text-[10px]"></i></button>
                                    <input type="file" ref={fileRef} accept="image/*" hidden onChange={e => setAvatarFile(e.target.files[0])} />
                                </div>
                                <div className="w-full">
                                    <label className="text-[10px] font-bold text-gray-400 ml-1">公開暱稱</label>
                                    <input value={editNickname} onChange={e=>setEditNickname(e.target.value)} className="w-full bg-gray-50 border border-gray-200 rounded-xl p-3 text-sm font-bold outline-none focus:border-blue-400 shadow-inner mt-1 text-center" />
                                </div>
                            </div>
                            <button onClick={saveProfile} className="w-full py-3 bg-gray-900 text-white rounded-xl text-sm font-black shadow-md active:scale-95 transition-transform">儲存個人資料</button>
                        </div>

                        <div className="bg-white rounded-3xl p-2 shadow-sm border border-gray-100/50">
                            <div className="flex items-center justify-between p-4">
                                <div className="flex items-center gap-3"><div className="w-10 h-10 rounded-2xl bg-blue-50 text-blue-500 flex items-center justify-center"><i className="fas fa-envelope"></i></div><div><div className="text-sm font-black text-gray-800">Email 系統通知</div><div className="text-[10px] text-gray-400 font-medium">接收好友邀請與重要平台公告</div></div></div>
                                <button onClick={toggleEmailNotify} className={`w-12 h-7 rounded-full relative transition-colors shadow-inner flex-shrink-0 ${emailNotify ? 'bg-green-500' : 'bg-gray-200'}`}><div className={`absolute top-1 w-5 h-5 bg-white rounded-full shadow transition-transform ${emailNotify ? 'left-6' : 'left-1'}`}></div></button>
                            </div>
                        </div>
                    </div>
                )}
                {tab === 'security' && (
                    <div className="space-y-3 animate-fadeIn">
                        <div className="bg-white rounded-3xl shadow-sm border border-gray-100/50 overflow-hidden">
                            <div className="border-b border-gray-50">
                                <button onClick={() => toggleSection('verify')} className="w-full flex items-center justify-between p-5 text-left hover:bg-gray-50 transition-colors"><div className="flex items-center gap-3"><div className={`w-10 h-10 rounded-2xl flex items-center justify-center ${user.isEmailVerified ? 'bg-green-50 text-green-500' : 'bg-yellow-50 text-yellow-500'}`}><i className="fas fa-check-shield"></i></div><div><div className="text-sm font-black text-gray-800">信箱驗證狀態</div><div className="text-[10px] text-gray-400 font-medium">{user.email}</div></div></div><div className="flex items-center gap-3"><span className={`text-[10px] font-black px-2 py-1 rounded-lg ${user.isEmailVerified ? 'bg-green-100 text-green-600' : 'bg-yellow-100 text-yellow-600'}`}>{user.isEmailVerified ? '已驗證' : '未驗證'}</span><i className={`fas fa-chevron-down text-gray-300 transition-transform ${activeSection === 'verify' ? 'rotate-180' : ''}`}></i></div></button>
                                {activeSection === 'verify' && !user.isEmailVerified && (
                                    <div className="px-5 pb-5 pt-2 animate-fadeIn bg-gray-50/50"><div className="flex flex-col gap-3"><div className="flex gap-2"><input value={verifyCode} onChange={e=>setVerifyCode(e.target.value)} placeholder="輸入6碼驗證碼" className="flex-1 bg-white border border-gray-200 rounded-xl p-3 text-sm font-bold outline-none focus:border-blue-400 shadow-inner" /><button onClick={() => sendVerifyCode(user.email)} disabled={isSending} className="bg-blue-100 text-blue-600 px-4 rounded-xl text-xs font-black active:scale-95 whitespace-nowrap">發送驗證信</button></div><button onClick={verifyCurrentEmail} className="w-full py-3.5 bg-gray-900 text-white rounded-xl text-sm font-black shadow-md active:scale-95">確認並驗證</button></div></div>
                                )}
                            </div>
                            <div className="border-b border-gray-50">
                                <button onClick={() => toggleSection('changeEmail')} className="w-full flex items-center justify-between p-5 text-left hover:bg-gray-50 transition-colors"><div className="flex items-center gap-3"><div className="w-10 h-10 rounded-2xl bg-blue-50 text-blue-500 flex items-center justify-center"><i className="fas fa-envelope-open-text"></i></div><div className="text-sm font-black text-gray-800">更改登入信箱</div></div><i className={`fas fa-chevron-down text-gray-300 transition-transform ${activeSection === 'changeEmail' ? 'rotate-180' : ''}`}></i></button>
                                {activeSection === 'changeEmail' && (
                                    <div className="px-5 pb-5 pt-2 animate-fadeIn bg-gray-50/50"><div className="flex flex-col gap-3"><input value={newEmail} onChange={e=>setNewEmail(e.target.value)} type="email" placeholder="輸入新的電子郵件" className="w-full bg-white border border-gray-200 rounded-xl p-3 text-sm font-bold outline-none focus:border-blue-400 shadow-inner" /><div className="flex gap-2"><input value={emailChangeCode} onChange={e=>setEmailChangeCode(e.target.value)} placeholder="輸入新信箱驗證碼" className="flex-1 bg-white border border-gray-200 rounded-xl p-3 text-sm font-bold outline-none focus:border-blue-400 shadow-inner" /><button onClick={() => sendVerifyCode(newEmail)} disabled={isSending || !newEmail} className="bg-blue-100 text-blue-600 px-4 rounded-xl text-xs font-black active:scale-95 whitespace-nowrap disabled:opacity-50">發送驗證信</button></div><button onClick={changeEmail} className="w-full py-3.5 bg-gray-900 text-white rounded-xl text-sm font-black shadow-md active:scale-95">確認更改信箱</button></div></div>
                                )}
                            </div>
                            <div>
                                <button onClick={() => toggleSection('changePwd')} className="w-full flex items-center justify-between p-5 text-left hover:bg-gray-50 transition-colors"><div className="flex items-center gap-3"><div className="w-10 h-10 rounded-2xl bg-purple-50 text-purple-500 flex items-center justify-center"><i className="fas fa-key"></i></div><div className="text-sm font-black text-gray-800">更改登入密碼</div></div><i className={`fas fa-chevron-down text-gray-300 transition-transform ${activeSection === 'changePwd' ? 'rotate-180' : ''}`}></i></button>
                                {activeSection === 'changePwd' && (
                                    <div className="px-5 pb-5 pt-2 animate-fadeIn bg-gray-50/50"><div className="flex flex-col gap-3"><div className="flex gap-2"><input value={pwdChangeCode} onChange={e=>setPwdChangeCode(e.target.value)} placeholder="目前信箱收到的驗證碼" className="flex-1 bg-white border border-gray-200 rounded-xl p-3 text-sm font-bold outline-none focus:border-purple-400 shadow-inner" /><button onClick={() => sendVerifyCode(user.email)} disabled={isSending} className="bg-purple-100 text-purple-600 px-4 rounded-xl text-xs font-black active:scale-95 whitespace-nowrap">發送驗證信</button></div><input value={newPwd} onChange={e=>setNewPwd(e.target.value)} type="password" placeholder="新密碼 (至少8碼)" className="w-full bg-white border border-gray-200 rounded-xl p-3 text-sm font-bold outline-none focus:border-purple-400 shadow-inner" /><input value={confNewPwd} onChange={e=>setConfNewPwd(e.target.value)} type="password" placeholder="再次確認新密碼" className={`w-full bg-white border rounded-xl p-3 text-sm font-bold outline-none focus:border-purple-400 shadow-inner ${newPwd && confNewPwd && newPwd !== confNewPwd ? 'border-red-400' : 'border-gray-200'}`} /><button onClick={changePassword} className="w-full py-3.5 bg-purple-600 text-white rounded-xl text-sm font-black shadow-md active:scale-95">確認更改密碼</button></div></div>
                                )}
                            </div>
                        </div>
                    </div>
                )}
            </div>
        </div>
    );
}

function ReportModal({ onClose }) {
    const [type, setType] = useState('bug');
    const [content, setContent] = useState('');
    const [isSubmitting, setIsSubmitting] = useState(false);

    const submit = async () => {
        if (!content.trim()) return alert('請輸入內容');
        setIsSubmitting(true);
        try {
            await secureFetch('/api/reports', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ type, content }) });
            alert('感謝您的回報！我們將盡快處理。'); onClose();
        } catch (e) { alert('回報失敗，請稍後再試'); }
        setIsSubmitting(false);
    };

    return (
        <div className="fixed inset-0 z-[100] bg-black/60 backdrop-blur-sm flex items-center justify-center p-4 animate-fadeIn">
            <div className="bg-white rounded-3xl w-full max-w-sm p-6 shadow-2xl relative animate-modalPop">
                <button onClick={onClose} className="absolute top-4 right-4 w-8 h-8 bg-gray-100 rounded-full text-gray-500 hover:bg-gray-200 transition-colors"><i className="fas fa-times"></i></button>
                <h2 className="text-xl font-black text-gray-800 mb-5 flex items-center"><i className="fas fa-paper-plane text-blue-500 mr-2"></i>回報與建議</h2>
                <div className="flex bg-gray-100 p-1 rounded-xl mb-4 shadow-inner">
                    <button onClick={() => setType('bug')} className={`flex-1 py-2 rounded-lg text-sm font-bold transition-colors ${type === 'bug' ? 'bg-white text-red-500 shadow-sm' : 'text-gray-500'}`}><i className="fas fa-bug mr-1"></i> Bug 回報</button>
                    <button onClick={() => setType('suggestion')} className={`flex-1 py-2 rounded-lg text-sm font-bold transition-colors ${type === 'suggestion' ? 'bg-white text-blue-500 shadow-sm' : 'text-gray-500'}`}><i className="fas fa-lightbulb mr-1"></i> 功能建議</button>
                </div>
                <textarea value={content} onChange={e => setContent(e.target.value)} placeholder="請詳細描述您遇到的問題或您的好點子..." className="w-full bg-gray-50 border border-gray-200 rounded-xl p-4 h-32 outline-none focus:border-blue-400 text-sm mb-4 font-medium shadow-inner resize-none" />
                <button onClick={submit} disabled={isSubmitting} className="w-full bg-blue-600 text-white py-3.5 rounded-xl font-black shadow-lg shadow-blue-200 active:scale-95 disabled:opacity-50 transition-transform">{isSubmitting ? '送出中...' : '確認送出'}</button>
            </div>
        </div>
    );
}

function RestTimerView({ onBack, onSaveToPost }) {
    const [timeLeft, setTimeLeft] = useState(0);
    const [initialTime, setInitialTime] = useState(60); 
    const [isRunning, setIsRunning] = useState(false);
    
    const [exName, setExName] = useState('');
    const [muscle, setMuscle] = useState('胸');
    const [curWeight, setCurWeight] = useState('');
    const [curReps, setCurReps] = useState('');
    
    const [workoutExercises, setWorkoutExercises] = useState([]);
    const [showExList, setShowExList] = useState(false);

    useEffect(() => {
        let timer;
        if (isRunning && timeLeft > 0) {
            timer = setInterval(() => setTimeLeft(prev => prev - 1), 1000);
        } else if (timeLeft === 0 && isRunning) {
            setIsRunning(false);
            if (window.navigator && window.navigator.vibrate) window.navigator.vibrate([200, 100, 200]); 
            alert('休息時間結束！準備下一組 💪');
        }
        return () => clearInterval(timer);
    }, [isRunning, timeLeft]);

    const formatTime = (sec) => {
        const m = Math.floor(sec / 60);
        const s = sec % 60;
        return `${m}:${s < 10 ? '0' : ''}${s}`;
    };

    const startTimer = (sec) => {
        setTimeLeft(sec);
        setInitialTime(sec);
        setIsRunning(true);
    };

    const handleAddSet = () => {
        if (!exName.trim()) return alert('請先輸入或選擇一個動作名稱');
        if (!curWeight || !curReps) return alert('請輸入重量與次數');
        
        const newExList = [...workoutExercises];
        const existingExIndex = newExList.findIndex(e => e.name === exName);
        
        if (existingExIndex >= 0) {
            newExList[existingExIndex].sets.push({ weight: curWeight, reps: curReps });
        } else {
            newExList.push({ name: exName, muscle: muscle, sets: [{ weight: curWeight, reps: curReps }] });
        }
        
        setWorkoutExercises(newExList);
        setCurReps(''); 
    };

    const handleFinish = () => {
        if (workoutExercises.length === 0) return alert('請至少完成一組訓練才能發佈喔！');
        onSaveToPost(workoutExercises);
    };

    const dbList = (window.EXERCISE_DB && window.EXERCISE_DB[muscle]) ? window.EXERCISE_DB[muscle] : [];

    return (
        <div className="absolute inset-0 z-50 bg-gray-50 text-gray-800 flex flex-col animate-slideDown overflow-hidden">
            <header className="px-5 py-4 flex items-center justify-between border-b border-gray-200 bg-white sticky top-0 z-20 shadow-sm">
                <button onClick={onBack} className="w-10 h-10 bg-gray-100 rounded-full flex items-center justify-center text-gray-500 hover:bg-gray-200 transition-colors"><i className="fas fa-times"></i></button>
                <h2 className="text-lg font-black tracking-widest text-orange-500"><i className="fas fa-stopwatch mr-2"></i>組間計時器</h2>
                <div className="w-10"></div>
            </header>
            
            <div className="flex-1 flex flex-col items-center p-5 overflow-y-auto pb-24">
                
                <div className="w-full max-w-sm px-2 mb-8 mt-6">
                    <div className="text-7xl font-black font-mono tracking-tighter text-gray-800 text-center mb-6 drop-shadow-sm">
                        {formatTime(timeLeft)}
                    </div>
                    <div className="w-full h-4 bg-gray-200 rounded-full overflow-hidden shadow-inner">
                        <div 
                            className="h-full bg-orange-500 rounded-full"
                            style={{ 
                                width: `${timeLeft > 0 ? (timeLeft / initialTime) * 100 : 0}%`,
                                transition: 'width 1s linear' 
                            }}
                        ></div>
                    </div>
                </div>
                
                <div className="flex gap-4 mb-5 w-full justify-center">
                    <button onClick={() => setTimeLeft(prev => Math.max(0, prev - 10))} className="w-16 bg-white border border-gray-200 py-3 rounded-2xl font-black text-gray-500 active:scale-90 transition-transform shadow-sm">-10s</button>
                    <button onClick={() => setIsRunning(!isRunning)} className={`px-10 py-3 rounded-2xl font-black text-lg active:scale-95 transition-all ${isRunning ? 'bg-red-50 text-red-500 border border-red-200' : 'bg-orange-500 text-white shadow-lg shadow-orange-500/30'}`}>{isRunning ? '暫停' : '開始計時'}</button>
                    <button onClick={() => setTimeLeft(prev => prev + 10)} className="w-16 bg-white border border-gray-200 py-3 rounded-2xl font-black text-gray-500 active:scale-90 transition-transform shadow-sm">+10s</button>
                </div>
                <div className="flex gap-3 mb-8 w-full justify-center">
                    <button onClick={() => startTimer(60)} className="flex-1 max-w-[80px] bg-white border border-gray-200 text-gray-600 py-2 rounded-xl text-sm font-black active:scale-95 shadow-sm hover:bg-gray-50">60s</button>
                    <button onClick={() => startTimer(90)} className="flex-1 max-w-[80px] bg-white border border-gray-200 text-gray-600 py-2 rounded-xl text-sm font-black active:scale-95 shadow-sm hover:bg-gray-50">90s</button>
                    <button onClick={() => startTimer(120)} className="flex-1 max-w-[80px] bg-white border border-gray-200 text-gray-600 py-2 rounded-xl text-sm font-black active:scale-95 shadow-sm hover:bg-gray-50">120s</button>
                </div>

                <div className="w-full bg-white rounded-3xl p-5 border border-gray-100 shadow-md relative">
                    <h3 className="text-sm font-black text-gray-800 mb-4 flex items-center gap-2"><i className="fas fa-pen text-orange-500"></i> 記錄這組動作</h3>
                    
                    <div className="flex gap-2 mb-3 relative">
                        <select value={muscle} onChange={e=>setMuscle(e.target.value)} className="bg-gray-50 border border-gray-200 text-gray-700 rounded-xl px-3 py-3 text-sm font-bold outline-none focus:border-orange-400">
                            <option value="胸">胸</option><option value="背">背</option><option value="腿">腿</option>
                            <option value="肩">肩</option><option value="手">手</option><option value="核心">核心</option>
                            <option value="有氧與其他">有氧/其他</option>
                        </select>
                        <input value={exName} onChange={e => { setExName(e.target.value); setShowExList(true); }} onFocus={() => setShowExList(true)} placeholder="動作名稱 (如: 臥推)" className="flex-1 w-full bg-gray-50 border border-gray-200 text-gray-800 rounded-xl px-4 py-3 text-sm font-bold outline-none focus:border-orange-400 shadow-inner" />
                        
                        {showExList && (
                            <>
                                <div className="fixed inset-0 z-10" onClick={() => setShowExList(false)}></div>
                                <div className="absolute top-full right-0 w-[70%] mt-2 bg-white border border-gray-200 rounded-xl shadow-2xl z-20 max-h-48 overflow-y-auto">
                                    {exName.trim() === '' ? (
                                        dbList.length > 0 ? dbList.map(ex => (
                                            <div key={ex} onClick={() => {setExName(ex); setShowExList(false);}} className="p-3 border-b border-gray-50 hover:bg-orange-50 cursor-pointer text-xs font-bold text-gray-700">{ex}</div>
                                        )) : <div className="p-3 text-xs text-gray-500 text-center bg-gray-50">請直接輸入動作</div>
                                    ) : (
                                        Object.entries(window.EXERCISE_DB || {}).flatMap(([m, exs]) => exs.filter(e => e.toLowerCase().includes(exName.toLowerCase())).map(e => ({m, e}))).map(item => (
                                            <div key={item.e} onClick={() => {setExName(item.e); setMuscle(item.m); setShowExList(false);}} className="p-3 border-b border-gray-50 hover:bg-orange-50 cursor-pointer text-xs font-bold text-gray-700 flex justify-between">{item.e} <span className="text-[9px] bg-orange-100 text-orange-600 px-2 py-0.5 rounded-full">{item.m}</span></div>
                                        ))
                                    )}
                                </div>
                            </>
                        )}
                    </div>

                    <div className="flex gap-2 mb-5">
                        <div className="flex-1 bg-gray-50 border border-gray-200 rounded-xl px-4 py-2 focus-within:border-orange-400 shadow-inner">
                            <div className="text-[10px] text-gray-500 font-bold mb-1">重量 (kg)</div>
                            <input type="number" value={curWeight} onChange={e=>setCurWeight(e.target.value)} placeholder="0" className="w-full bg-transparent outline-none text-gray-800 font-black text-xl" />
                        </div>
                        <div className="flex-1 bg-gray-50 border border-gray-200 rounded-xl px-4 py-2 focus-within:border-orange-400 shadow-inner">
                            <div className="text-[10px] text-gray-500 font-bold mb-1">次數 (reps)</div>
                            <input type="number" value={curReps} onChange={e=>setCurReps(e.target.value)} placeholder="0" className="w-full bg-transparent outline-none text-gray-800 font-black text-xl" />
                        </div>
                        <button onClick={handleAddSet} className="bg-orange-100 text-orange-600 border border-orange-200 rounded-xl px-5 font-black active:scale-95 transition-transform"><i className="fas fa-plus mb-1"></i><br/><span className="text-[10px]">加入</span></button>
                    </div>

                    {workoutExercises.length > 0 && (
                        <div className="space-y-3 mb-5 max-h-48 overflow-y-auto pr-1">
                            {workoutExercises.map((ex, exIdx) => (
                                <div key={exIdx} className="bg-gray-50 p-3 rounded-xl border border-gray-200 relative shadow-sm">
                                    <div className="font-black text-sm text-gray-800 mb-2 pr-6">{ex.name} <span className="text-[10px] bg-blue-100 text-blue-600 px-1.5 py-0.5 rounded-full ml-1">{ex.muscle}</span></div>
                                    <button onClick={() => { const newEx = [...workoutExercises]; newEx.splice(exIdx,1); setWorkoutExercises(newEx); }} className="absolute top-3 right-3 text-red-400 hover:text-red-600"><i className="fas fa-times"></i></button>
                                    
                                    <div className="space-y-1.5">
                                        {ex.sets.map((s, sIdx) => (
                                            <div key={sIdx} className="flex justify-between items-center text-[11px] font-bold text-gray-500 border-b border-gray-100 pb-1.5 last:border-0 last:pb-0">
                                                <span className="bg-white border border-gray-200 px-2 py-0.5 rounded text-gray-400">組 {sIdx+1}</span>
                                                <span className="text-gray-800 bg-white px-3 py-1 rounded shadow-sm">{s.weight} kg <span className="text-orange-400 mx-1">×</span> {s.reps} 下</span>
                                            </div>
                                        ))}
                                    </div>
                                </div>
                            ))}
                        </div>
                    )}

                    <button onClick={handleFinish} className="w-full bg-gray-900 text-white py-3.5 rounded-xl font-black text-sm active:scale-95 transition-transform shadow-md flex items-center justify-center gap-2">
                        完成訓練並發佈動態 <i className="fas fa-arrow-right"></i>
                    </button>
                </div>
            </div>
        </div>
    );
}

function OnboardingModal({ user, onComplete }) {
    return (
        <div className="fixed inset-0 z-[300] bg-blue-600 flex flex-col items-center justify-center p-6 animate-fadeIn text-white">
            <div className="text-center w-full max-w-sm overflow-y-auto max-h-[90vh] scrollbar-hide py-4">
                <div className="w-24 h-24 bg-white rounded-full mx-auto flex items-center justify-center mb-6 shadow-2xl flex-shrink-0 overflow-hidden border-4 border-white text-blue-600">
                    {user.avatar ? <img src={user.avatar.startsWith('http') || user.avatar.startsWith('data:') ? user.avatar : SERVER_URL + user.avatar} className="w-full h-full object-cover flex-shrink-0"/> : <i className="fas fa-fire text-5xl"></i>}
                </div>
                <h1 className="text-3xl font-black italic mb-2">哈囉，{user.nickname}！</h1>
                <p className="text-sm font-bold text-blue-200 mb-10">歡迎來到 Afitus</p>
                <div className="space-y-6 text-left bg-white/10 p-6 rounded-3xl mb-8">
                    <div className="flex items-start gap-4">
                        <div className="w-10 h-10 rounded-full bg-orange-500 flex items-center justify-center flex-shrink-0 shadow-md mt-0.5"><i className="fas fa-chart-line text-white text-sm"></i></div>
                        <div><h3 className="font-black text-sm">專屬數據儀表板</h3><p className="text-xs text-blue-100 mt-1 font-medium leading-relaxed">記錄卡路里與運動時長，自動生成趨勢圖表。</p></div>
                    </div>
                    <div className="flex items-start gap-4">
                        <div className="w-10 h-10 rounded-full bg-green-500 flex items-center justify-center flex-shrink-0 shadow-md mt-0.5"><i className="fas fa-utensils text-white text-sm"></i></div>
                        <div><h3 className="font-black text-sm">精準飲食打卡</h3><p className="text-xs text-blue-100 mt-1 font-medium leading-relaxed">拍照讓 AI 自動為你計算三大營養素。</p></div>
                    </div>
                    <div className="flex items-start gap-4">
                        <div className="w-10 h-10 rounded-full bg-purple-500 flex items-center justify-center flex-shrink-0 shadow-md mt-0.5"><i className="fas fa-robot text-white text-sm"></i></div>
                        <div><h3 className="font-black text-sm">Afitus AI</h3><p className="text-xs text-blue-100 mt-1 font-medium leading-relaxed">您的專屬 AI 夥伴，隨時為您解答健身問題。</p></div>
                    </div>
                </div>
                <div className="mt-8 font-bold text-xs text-blue-200 bg-black/20 py-3 px-5 rounded-full inline-block shadow-inner">
                    專屬 ID: <span className="text-white ml-1.5 text-sm">{user.fitId}</span>
                </div>
                <button onClick={onComplete} className="w-full mt-8 py-4 bg-white text-blue-600 rounded-2xl font-black text-lg shadow-xl active:scale-95 transition-transform">開始探索</button>
            </div>
        </div>
    );
}
// ==========================================
// 4. 登入註冊與管理員後台區塊
// ==========================================

function AuthPage({ authView, setAuthView, handleAuth, onAdminLogin }) {
    const [e, setE] = useState(''); const [p, setP] = useState(''); const [c, setC] = useState(''); const [n, setN] = useState('');
    const [agree, setAgree] = useState(false); const [hasReadTerms, setHasReadTerms] = useState(false);
    const [remember, setRemember] = useState(true); const [showPolicy, setShowPolicy] = useState(false);
    const [isSaving, setIsSaving] = useState(false); const [showPwd, setShowPwd] = useState(false);
    const [showAdminAuth, setShowAdminAuth] = useState(false);

    const [resetStep, setResetStep] = useState(1);
    const [otp, setOtp] = useState('');
    const [newPassword, setNewPassword] = useState('');
    const [confirmNewPassword, setConfirmNewPassword] = useState(''); 
    const [showNewPwd, setShowNewPwd] = useState(false); 

    const handleForgotPassword = async (step) => {
        setIsSaving(true);
        try {
            if (step === 1) {
                if (!e) throw new Error('請輸入電子郵件');
                const res = await secureFetch('/api/auth/forgot-password-send', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ email: e }) });
                if (!res.ok) { const data = await res.json(); throw new Error(data.error); }
                alert('驗證碼已發送至您的信箱！');
                setResetStep(2);
            } else {
                if (!otp || newPassword.length < 8) throw new Error('請填寫6位數驗證碼與新密碼(至少8碼)');
                if (newPassword !== confirmNewPassword) throw new Error('兩次輸入的新密碼不一致！');
                
                const res = await secureFetch('/api/auth/forgot-password-reset', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ email: e, code: otp, newPassword: newPassword }) });
                if (!res.ok) { const data = await res.json(); throw new Error(data.error); }
                alert('密碼重設成功！請使用新密碼登入');
                setAuthView('login'); setResetStep(1); setP(''); setOtp(''); setNewPassword(''); setConfirmNewPassword('');
            }
        } catch (err) {
            alert(err.message || '操作失敗');
        } finally {
            setIsSaving(false);
        }
    };
    
    return (
        <div className="min-h-[100dvh] w-full max-w-md mx-auto bg-white p-6 flex flex-col justify-center animate-fadeIn relative pb-16">
            {showPolicy && <PrivacyModal onClose={() => setShowPolicy(false)} onReadComplete={() => setHasReadTerms(true)} />}
            {showAdminAuth && <AdminAuthModal onClose={() => setShowAdminAuth(false)} onLoginSuccess={onAdminLogin} />}

            <div className="text-center mb-8"><div className="bg-blue-600 w-20 h-20 rounded-[2rem] flex items-center justify-center mx-auto mb-4 shadow-xl shadow-blue-200 rotate-6"><i className="fas fa-fire text-white text-4xl"></i></div><h1 className="text-4xl font-black italic text-blue-600 uppercase tracking-tighter">Afitus</h1><p className="text-gray-400 text-[10px] font-black tracking-[0.2em] mt-1.5">BEYOND LIMITS</p></div>
            
            {authView !== 'forgot' && (<div className="flex bg-gray-100 p-1 rounded-2xl mb-6 shadow-inner"><button type="button" onClick={() => {setAuthView('login'); setAgree(false);}} className={`flex-1 py-3 rounded-xl text-sm font-black transition-all ${authView === 'login' ? 'bg-white shadow text-blue-600' : 'text-gray-400'}`}>登入</button><button type="button" onClick={() => {setAuthView('register'); setAgree(false);}} className={`flex-1 py-3 rounded-xl text-sm font-black transition-all ${authView === 'register' ? 'bg-white shadow text-blue-600' : 'text-gray-400'}`}>註冊</button></div>)}

            {authView === 'forgot' ? (
                <div className="space-y-4 animate-fadeIn">
                    <h2 className="text-lg font-black text-gray-800 text-center mb-4">重設密碼</h2>
                    <div className="relative">
                        <i className="fas fa-envelope absolute left-4 top-1/2 -translate-y-1/2 text-gray-400 text-sm"></i>
                        <input name="forgot-email" autoComplete="email" type="email" disabled={resetStep === 2} className="w-full bg-gray-50 border border-gray-100 rounded-2xl py-3.5 pl-11 pr-4 outline-none font-bold text-sm disabled:bg-gray-200 focus:border-blue-400" placeholder="您註冊時的電子郵件" value={e} onChange={v => setE(v.target.value)} />
                    </div>
                    {resetStep === 2 && (
                        <>
                            <input name="forgot-code" autoComplete="off" type="text" className="w-full bg-blue-50 border border-blue-100 rounded-2xl py-3.5 px-4 outline-none font-bold text-sm tracking-[0.5em] text-center focus:border-blue-400" placeholder="郵件中收到的 6 位數" value={otp} onChange={v => setOtp(v.target.value)} maxLength="6" />
                            <div className="relative">
                                <i className="fas fa-lock absolute left-4 top-1/2 -translate-y-1/2 text-gray-400 text-sm"></i>
                                <input name="new-password" autoComplete="new-password" type={showNewPwd ? "text" : "password"} className="w-full bg-gray-50 border border-gray-100 rounded-2xl py-3.5 pl-11 pr-12 outline-none font-bold text-sm focus:border-blue-400" placeholder="設定新的密碼 (至少 8 碼)" value={newPassword} onChange={v => setNewPassword(v.target.value)} />
                                <button type="button" onClick={() => setShowNewPwd(!showNewPwd)} className="absolute right-4 top-1/2 -translate-y-1/2 text-gray-400 flex items-center justify-center h-full focus:outline-none"><i className={showNewPwd ? "fas fa-eye" : "fas fa-eye-slash"}></i></button>
                            </div>
                            <div className="relative">
                                <i className="fas fa-check absolute left-4 top-1/2 -translate-y-1/2 text-gray-400 text-sm"></i>
                                <input name="confirm-new-password" autoComplete="new-password" type={showNewPwd ? "text" : "password"} className={`w-full bg-gray-50 border rounded-2xl py-3.5 pl-11 pr-4 outline-none font-bold text-sm focus:border-blue-400 ${newPassword && confirmNewPassword && newPassword !== confirmNewPassword ? 'border-red-400' : 'border-gray-100'}`} placeholder="再次輸入新密碼以確認" value={confirmNewPassword} onChange={v => setConfirmNewPassword(v.target.value)} />
                            </div>
                        </>
                    )}
                    <button type="button" onClick={() => handleForgotPassword(resetStep)} disabled={isSaving || (resetStep === 2 && (!newPassword || newPassword !== confirmNewPassword || otp.length !== 6))} className="w-full py-4 bg-blue-600 text-white rounded-2xl font-black text-sm shadow-md active:scale-95 disabled:opacity-50 transition-colors mt-2">{isSaving ? '處理中...' : (resetStep === 1 ? '獲取重設驗證碼' : '確認套用新密碼')}</button>
                    <button type="button" onClick={() => { setAuthView('login'); setResetStep(1); setNewPassword(''); setConfirmNewPassword(''); setOtp(''); }} className="w-full py-2 text-gray-400 text-xs font-bold hover:text-gray-600 transition-colors">返回登入畫面</button>
                </div>
            ) : (
                <form className="space-y-3" onSubmit={ev => handleAuth(ev, e, p, c, n, setIsSaving, remember)}>
                    {authView === 'register' && (
                        <div className="relative">
                            <i className="fas fa-user absolute left-4 top-1/2 -translate-y-1/2 text-gray-400 text-sm"></i>
                            <input name="nickname" autoComplete="username" className="w-full bg-gray-50 border border-gray-100 rounded-2xl py-3.5 pl-11 pr-4 outline-none font-bold text-sm focus:border-blue-500" placeholder="公開暱稱" value={n} onChange={v => setN(v.target.value)} required />
                        </div>
                    )}
                    <div className="relative">
                        <i className="fas fa-envelope absolute left-4 top-1/2 -translate-y-1/2 text-gray-400 text-sm"></i>
                        <input name="email" autoComplete="email" type="email" className="w-full bg-gray-50 border border-gray-100 rounded-2xl py-3.5 pl-11 pr-4 outline-none font-bold text-sm focus:border-blue-500" placeholder="電子郵件" value={e} onChange={v => setE(v.target.value)} required />
                    </div>
                    <div className="relative">
                        <i className="fas fa-lock absolute left-4 top-1/2 -translate-y-1/2 text-gray-400 text-sm"></i>
                        <input name="password" autoComplete={authView === 'login' ? 'current-password' : 'new-password'} type={showPwd ? "text" : "password"} className="w-full bg-gray-50 border border-gray-100 rounded-2xl py-3.5 pl-11 pr-12 outline-none font-bold text-sm focus:border-blue-500" placeholder="密碼 (至少 8 碼)" value={p} onChange={v => setP(v.target.value)} required minLength="8" />
                        <button type="button" onClick={() => setShowPwd(!showPwd)} className="absolute right-4 top-1/2 -translate-y-1/2 text-gray-400 h-full flex items-center justify-center focus:outline-none"><i className={showPwd ? "fas fa-eye" : "fas fa-eye-slash"}></i></button>
                    </div>
                    {authView === 'register' && (
                        <div className="relative">
                            <i className="fas fa-shield-alt absolute left-4 top-1/2 -translate-y-1/2 text-gray-400 text-sm"></i>
                            <input name="confirm-password" autoComplete="new-password" type={showPwd ? "text" : "password"} className={`w-full bg-gray-50 border rounded-2xl py-3.5 pl-11 pr-12 outline-none font-bold text-sm focus:border-blue-500 ${p && c && p !== c ? 'border-red-400' : 'border-gray-100'}`} placeholder="確認密碼" value={c} onChange={v => setC(v.target.value)} required minLength="8" />
                        </div>
                    )}
                    
                    {authView === 'login' && <div className="text-right pt-1"><button type="button" onClick={() => { setAuthView('forgot'); setE(''); setP(''); setOtp(''); setResetStep(1); }} className="text-xs font-bold text-blue-600 hover:text-blue-800 transition-colors">忘記密碼？</button></div>}

                    <div className="space-y-3 pt-2 px-1.5">
                        {authView === 'login' && (
                            <div className="flex items-center gap-2"><input type="checkbox" id="remember" checked={remember} onChange={e => setRemember(e.target.checked)} className="w-4 h-4 cursor-pointer accent-blue-600 rounded" /><label htmlFor="remember" className="text-xs text-gray-600 font-bold cursor-pointer select-none">保持登入 (30天)</label></div>
                        )}
                        <div className="flex items-start gap-2"><input type="checkbox" id="agree" checked={agree} onChange={e => setAgree(e.target.checked)} disabled={authView === 'register' && !hasReadTerms} className="mt-0.5 w-4 h-4 cursor-pointer accent-blue-600 rounded disabled:opacity-50" /><label htmlFor="agree" className="text-xs text-gray-600 font-bold cursor-pointer select-none">我同意本站 <span className="text-blue-600 underline cursor-pointer hover:text-blue-800" onClick={(e) => { e.preventDefault(); setShowPolicy(true); }}>隱私權政策與資料防護條款</span>{authView === 'register' && !hasReadTerms && <span className="text-red-500 ml-1">(請點擊閱讀)</span>}</label></div>
                    </div>

                    <button type="submit" className={`w-full py-4 text-white rounded-2xl font-black text-sm shadow-md mt-6 transition-all ${agree && !isSaving ? 'bg-blue-600 shadow-blue-200 active:scale-95' : 'bg-gray-300 shadow-none cursor-not-allowed'}`} disabled={!agree || isSaving}>{isSaving ? '處理中...' : (authView === 'login' ? '登入' : '註冊帳號')}</button>
                </form>
            )}
            
            <div className="absolute bottom-4 right-4 z-50">
                <button type="button" onClick={() => setShowAdminAuth(true)} className="text-gray-300 p-3 opacity-30 hover:opacity-100 transition-opacity"><i className="fas fa-server"></i></button>
            </div>
        </div>
    );
}

function AdminPanel({ onLogout }) {
    const [data, setData] = useState({ users:[], posts:[], comments:[], reports:[], stats:{} }); 
    const [tab, setTab] = useState('overview'); 
    const [query, setQuery] = useState(''); 
    const [loading, setLoading] = useState(true);
    const [settings, setSettings] = useState({ aiAutoPost: false });

    const fetchD = () => { 
        setLoading(true); 
        secureFetch('/api/admin/system_data')
            .then(r=>r.json())
            .then(d=>{setData(d); setLoading(false);})
            .catch(() => setLoading(false)); 
            
        secureFetch('/api/admin/settings')
            .then(r=>r.json())
            .then(s => setSettings(s))
            .catch(()=>{});
    };

    useEffect(() => { fetchD(); },[]);

    const action = async (msg, url, method='DELETE') => { 
        if(confirm(msg)) {
            try {
                const res = await secureFetch(url, { method });
                if (!res.ok) throw new Error('API 回傳錯誤');
                fetchD(); 
            } catch (err) {
                alert('操作失敗！請確認後端對應的 API 是否有錯誤。');
            }
        }
    };

    const toggleAiAutoPost = async () => {
        const newVal = !settings.aiAutoPost;
        try {
            const res = await secureFetch('/api/admin/settings', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ aiAutoPost: newVal })
            });
            if (res.ok) setSettings({ ...settings, aiAutoPost: newVal });
        } catch (e) {
            alert('設定失敗');
        }
    };

    const triggerAiPost = async () => {
        if (!confirm('確定要強制 AI 現在發布一篇新文章嗎？')) return;
        try {
            const res = await secureFetch('/api/admin/trigger-ai-post', { method: 'POST' });
            if (res.ok) {
                alert('AI 發文成功！');
                fetchD();
            } else {
                const data = await res.json();
                alert(data.error || '發文失敗');
            }
        } catch (e) {
            alert('發文失敗');
        }
    };

    if (loading && !data.stats?.userCount) return <div className="h-screen bg-gray-900 text-white flex items-center justify-center font-black text-2xl animate-pulse">載入中...</div>;
    
    const q = query.toLowerCase(); 
    const filtered = (arr, keys) => (arr||[]).filter(item => keys.some(k => (item[k]||'').toString().toLowerCase().includes(q)));

    return (
        <div className="h-screen bg-gray-900 text-gray-200 overflow-y-auto font-sans flex flex-col">
            <div className="bg-gray-900/90 backdrop-blur-lg border-b border-gray-800 sticky top-0 z-10 px-4 py-4 sm:px-6 shadow-md pt-safe">
                <div className="max-w-5xl mx-auto flex justify-between items-center mb-4"><h1 className="text-xl sm:text-2xl font-black text-white flex items-center gap-3"><div className="bg-blue-600 w-8 h-8 rounded-xl flex items-center justify-center shadow-lg shadow-blue-500/30"><i className="fas fa-server text-sm"></i></div> 控制中心</h1><button onClick={onLogout} className="bg-red-500/10 text-red-500 hover:bg-red-500 hover:text-white px-4 py-2 rounded-xl text-xs font-bold transition-all shadow-sm active:scale-95"><i className="fas fa-sign-out-alt sm:mr-1.5"></i><span className="hidden sm:inline">安全登出</span></button></div>
                <div className="max-w-5xl mx-auto flex gap-2 overflow-x-auto scrollbar-hide pb-1">
                    <button onClick={()=>setTab('overview')} className={`px-5 py-2.5 rounded-xl text-xs font-black whitespace-nowrap transition-all flex items-center gap-2 ${tab==='overview'?'bg-blue-600 text-white shadow-lg shadow-blue-500/30':'bg-gray-800 text-gray-400 hover:bg-gray-700'}`}><i className="fas fa-chart-pie"></i> 總覽</button>
                    <button onClick={()=>setTab('users')} className={`px-5 py-2.5 rounded-xl text-xs font-black whitespace-nowrap transition-all flex items-center gap-2 ${tab==='users'?'bg-blue-600 text-white shadow-lg shadow-blue-500/30':'bg-gray-800 text-gray-400 hover:bg-gray-700'}`}><i className="fas fa-users"></i> 用戶 <span className="bg-gray-900/50 px-1.5 py-0.5 rounded text-[10px]">{data.stats.userCount}</span></button>
                    <button onClick={()=>setTab('posts')} className={`px-5 py-2.5 rounded-xl text-xs font-black whitespace-nowrap transition-all flex items-center gap-2 ${tab==='posts'?'bg-blue-600 text-white shadow-lg shadow-blue-500/30':'bg-gray-800 text-gray-400 hover:bg-gray-700'}`}><i className="fas fa-images"></i> 貼文 <span className="bg-gray-900/50 px-1.5 py-0.5 rounded text-[10px]">{data.stats.postCount}</span></button>
                    <button onClick={()=>setTab('comments')} className={`px-5 py-2.5 rounded-xl text-xs font-black whitespace-nowrap transition-all flex items-center gap-2 ${tab==='comments'?'bg-blue-600 text-white shadow-lg shadow-blue-500/30':'bg-gray-800 text-gray-400 hover:bg-gray-700'}`}><i className="fas fa-comments"></i> 留言 <span className="bg-gray-900/50 px-1.5 py-0.5 rounded text-[10px]">{data.stats.commentCount}</span></button>
                    <button onClick={()=>setTab('reports')} className={`px-5 py-2.5 rounded-xl text-xs font-black whitespace-nowrap transition-all flex items-center gap-2 ${tab==='reports'?'bg-red-600 text-white shadow-lg shadow-red-500/30':'bg-gray-800 text-gray-400 hover:bg-gray-700'}`}><i className="fas fa-bug"></i> 回報 <span className="bg-gray-900/50 px-1.5 py-0.5 rounded text-[10px]">{data.stats.reportCount || 0}</span></button>
                    <button onClick={()=>setTab('settings')} className={`px-5 py-2.5 rounded-xl text-xs font-black whitespace-nowrap transition-all flex items-center gap-2 ${tab==='settings'?'bg-purple-600 text-white shadow-lg shadow-purple-500/30':'bg-gray-800 text-gray-400 hover:bg-gray-700'}`}><i className="fas fa-robot"></i> 系統設定</button>
                </div>
            </div>
            
            <div className="max-w-5xl mx-auto w-full p-4 sm:p-6 flex-1 flex flex-col gap-6 animate-fadeIn">
                {tab === 'overview' && (
                    <div className="grid grid-cols-2 sm:grid-cols-4 gap-4">
                        <div className="bg-gray-800/50 border border-gray-700 p-5 rounded-3xl flex flex-col items-center justify-center text-center shadow-lg"><div className="w-12 h-12 rounded-full bg-blue-500/10 text-blue-500 flex items-center justify-center mb-3 text-xl"><i className="fas fa-users"></i></div><div className="text-3xl font-black text-white">{data.stats.userCount}</div><div className="text-xs text-gray-400 font-bold mt-1">總註冊用戶</div></div>
                        <div className="bg-gray-800/50 border border-gray-700 p-5 rounded-3xl flex flex-col items-center justify-center text-center shadow-lg"><div className="w-12 h-12 rounded-full bg-green-500/10 text-green-500 flex items-center justify-center mb-3 text-xl"><i className="fas fa-images"></i></div><div className="text-3xl font-black text-white">{data.stats.postCount}</div><div className="text-xs text-gray-400 font-bold mt-1">平台總貼文</div></div>
                        <div className="bg-gray-800/50 border border-gray-700 p-5 rounded-3xl flex flex-col items-center justify-center text-center shadow-lg"><div className="w-12 h-12 rounded-full bg-purple-500/10 text-purple-500 flex items-center justify-center mb-3 text-xl"><i className="fas fa-comments"></i></div><div className="text-3xl font-black text-white">{data.stats.commentCount}</div><div className="text-xs text-gray-400 font-bold mt-1">累積留言數</div></div>
                        <div className="bg-gray-800/50 border border-gray-700 p-5 rounded-3xl flex flex-col items-center justify-center text-center shadow-lg"><div className="w-12 h-12 rounded-full bg-red-500/10 text-red-500 flex items-center justify-center mb-3 text-xl"><i className="fas fa-bug"></i></div><div className="text-3xl font-black text-white">{data.stats.reportCount || 0}</div><div className="text-xs text-gray-400 font-bold mt-1">待處理回報</div></div>
                    </div>
                )}
                
                {tab === 'settings' && (
                    <div className="bg-gray-800/40 rounded-3xl border border-gray-700/50 shadow-xl p-6">
                        <h2 className="text-xl font-black text-white mb-6 flex items-center gap-2"><i className="fas fa-robot text-purple-400"></i> AI 自動化設定</h2>
                        
                        <div className="bg-gray-900/50 border border-gray-700 p-5 rounded-2xl flex items-center justify-between mb-4">
                            <div className="pr-4">
                                <div className="font-bold text-white text-lg">AI 每日自動發文</div>
                                <div className="text-xs text-gray-400 mt-1 leading-relaxed">開啟後，系統每天會自動尋找一篇健身新知並發布到動態牆上。</div>
                            </div>
                            <button 
                                onClick={toggleAiAutoPost}
                                className={`w-14 h-8 rounded-full relative transition-colors flex-shrink-0 ${settings.aiAutoPost ? 'bg-green-500' : 'bg-gray-600'}`}
                            >
                                <div className={`absolute top-1 w-6 h-6 bg-white rounded-full transition-transform ${settings.aiAutoPost ? 'left-7' : 'left-1'}`}></div>
                            </button>
                        </div>

                        <div className="bg-gray-900/50 border border-gray-700 p-5 rounded-2xl flex items-center justify-between">
                            <div className="pr-4">
                                <div className="font-bold text-white text-lg">手動觸發 AI 發文</div>
                                <div className="text-xs text-gray-400 mt-1 leading-relaxed">立即讓 AI 產生一篇新文章並發布 (用於測試或手動更新)。</div>
                            </div>
                            <button 
                                onClick={triggerAiPost}
                                className="bg-purple-600 hover:bg-purple-500 text-white px-4 py-2.5 rounded-xl text-sm font-black transition-colors shadow-lg shadow-purple-500/30 flex-shrink-0"
                            >
                                <i className="fas fa-bolt mr-1"></i> 立即發布
                            </button>
                        </div>
                    </div>
                )}
                
                {tab !== 'overview' && tab !== 'settings' && ( <div className="relative"><i className="fas fa-search absolute left-5 top-1/2 -translate-y-1/2 text-gray-500"></i><input value={query} onChange={e=>setQuery(e.target.value)} className="w-full bg-gray-800/50 border border-gray-700 focus:border-blue-500 rounded-2xl py-4 pl-12 pr-4 outline-none font-bold text-white text-sm transition-all shadow-inner placeholder-gray-600" placeholder="在清單中搜尋..." /></div> )}
                
                {tab !== 'overview' && tab !== 'settings' && (
                    <div className="bg-gray-800/40 rounded-3xl border border-gray-700/50 shadow-xl overflow-hidden flex flex-col">
                        
                        {tab === 'users' && filtered(data.users,['email','nickname','fitId']).map((u, i) => (
                            <div key={u.email} className={`p-5 sm:p-6 flex flex-col sm:flex-row sm:items-center justify-between gap-5 hover:bg-gray-700/30 transition-colors ${i !== filtered(data.users, ['email']).length-1 ? 'border-b border-gray-700/50' : ''}`}>
                                <div className="flex items-center gap-4"><div className="w-14 h-14 rounded-full bg-gray-700 overflow-hidden flex-shrink-0 border border-gray-600 flex items-center justify-center">{u.avatar ? <img src={u.avatar.startsWith('http') ? u.avatar : SERVER_URL + u.avatar} className="w-full h-full object-cover flex-shrink-0"/> : <i className="fas fa-user text-gray-500 text-xl"></i>}</div><div className="flex-1 min-w-0"><div className="font-black text-white text-base truncate">{u.nickname} <span className="text-gray-500 text-xs font-bold ml-1">({u.email})</span></div><div className="text-xs text-gray-400 mt-1.5 font-bold flex flex-wrap gap-2"><span className="bg-gray-800 px-2 py-0.5 rounded border border-gray-700">ID: {u.fitId}</span> <span className="bg-gray-800 px-2 py-0.5 rounded border border-gray-700">貼文: {u.postCount}</span></div></div></div>
                                <div className="flex flex-row sm:flex-col gap-2 flex-shrink-0"><button onClick={()=>action('確定要清空該用戶的所有按讚紀錄嗎？', '/api/admin/users/'+u.email+'/clear_likes', 'POST')} className="flex-1 sm:flex-none bg-orange-500/10 text-orange-500 hover:bg-orange-500 hover:text-white px-4 py-2.5 rounded-xl text-xs font-bold transition-all"><i className="fas fa-eraser sm:mr-1"></i> 清空按讚</button><button onClick={()=>action('【警告】確定刪除帳號？此操作無法復原。', '/api/admin/users/'+u.email)} className="flex-1 sm:flex-none bg-red-500/10 text-red-500 hover:bg-red-500 hover:text-white px-4 py-2.5 rounded-xl text-xs font-bold transition-all"><i className="fas fa-trash-alt sm:mr-1"></i> 刪除帳號</button></div>
                            </div>
                        ))}

                        {tab === 'posts' && filtered(data.posts, ['content', 'userName', 'userId']).map((p, i) => (
                            <div key={p.id} className={`p-5 sm:p-6 flex flex-col sm:flex-row sm:items-center justify-between gap-5 hover:bg-gray-700/30 transition-colors ${i !== data.posts.length-1 ? 'border-b border-gray-700/50' : ''}`}>
                                <div className="flex-1 min-w-0 w-full">
                                    <div className="text-xs text-gray-400 mb-2 font-bold flex flex-wrap items-center gap-2"><span className="text-white">{p.userName}</span> <span className="font-normal text-gray-500">({p.userId})</span> <span className="text-[10px] text-gray-500">{new Date(p.timestamp).toLocaleString()}</span></div>
                                    <div className="text-sm text-gray-200 font-medium whitespace-pre-wrap leading-relaxed truncate">{p.content.split('===FITSHARE_WORKOUT===')[0] || '(無文字內容)'}</div>
                                    {p.images && p.images.length > 0 && <div className="text-xs text-blue-400 mt-2"><i className="fas fa-image"></i> 包含 {p.images.length} 張圖片</div>}
                                </div>
                                <button onClick={()=>action('確定要強制刪除此貼文？', '/api/admin/posts/'+p.id)} className="w-full sm:w-auto bg-red-500/10 text-red-500 hover:bg-red-500 hover:text-white px-5 py-3 rounded-xl text-xs font-bold transition-all flex-shrink-0 mt-1 sm:mt-0"><i className="fas fa-trash-alt mr-1.5"></i> 刪除貼文</button>
                            </div>
                        ))}

                        {tab === 'comments' && filtered(data.comments, ['text', 'userName', 'userId']).map((c, i) => (
                            <div key={c.id} className={`p-5 sm:p-6 flex flex-col sm:flex-row sm:items-center justify-between gap-5 hover:bg-gray-700/30 transition-colors ${i !== data.comments.length-1 ? 'border-b border-gray-700/50' : ''}`}>
                                <div className="flex-1 min-w-0 w-full">
                                    <div className="text-xs text-gray-400 mb-2 font-bold flex flex-wrap items-center gap-2"><span className="text-white">{c.userName}</span> <span className="font-normal text-gray-500">({c.userId})</span> <span className="text-[10px] text-gray-500">{new Date(c.timestamp).toLocaleString()}</span></div>
                                    <div className="text-sm text-gray-200 font-medium whitespace-pre-wrap leading-relaxed truncate">{c.text}</div>
                                </div>
                                <button onClick={()=>action('確定要強制刪除此留言？', '/api/admin/comments/'+c.id)} className="w-full sm:w-auto bg-red-500/10 text-red-500 hover:bg-red-500 hover:text-white px-5 py-3 rounded-xl text-xs font-bold transition-all flex-shrink-0 mt-1 sm:mt-0"><i className="fas fa-trash-alt mr-1.5"></i> 刪除留言</button>
                            </div>
                        ))}

                        {tab === 'reports' && (data.reports ||[]).filter(r => (r.content||'').toLowerCase().includes(q) || (r.userName||'').toLowerCase().includes(q)).map((r, i) => (
                            <div key={r.id} className={`p-5 sm:p-6 flex flex-col sm:flex-row justify-between items-start gap-4 hover:bg-gray-700/30 transition-colors ${i !== data.reports.length-1 ? 'border-b border-gray-700/50' : ''}`}>
                                <div className="flex-1 min-w-0 w-full"><div className="text-xs text-gray-400 mb-2 font-bold flex flex-wrap items-center gap-2">{r.type === 'bug' ? <span className="bg-red-500/20 text-red-400 px-2 py-0.5 rounded border border-red-500/20 flex-shrink-0">Bug 回報</span> : <span className="bg-blue-500/20 text-blue-400 px-2 py-0.5 rounded border border-blue-500/20 flex-shrink-0">功能建議</span>}<span className="text-white truncate max-w-[100px] sm:max-w-none">{r.userName}</span> <span className="font-normal text-gray-500 hidden sm:inline">({r.userId})</span> <span className="text-[10px] text-gray-500 flex-shrink-0">{new Date(r.timestamp).toLocaleString()}</span></div><div className="text-sm text-gray-200 font-medium whitespace-pre-wrap leading-relaxed break-words bg-gray-800/50 p-3 rounded-xl border border-gray-700/50">{r.content}</div></div>
                                <button onClick={()=>action('確定將此回報標示為已解決並刪除？', '/api/admin/reports/'+r.id)} className="w-full sm:w-auto bg-green-500/10 text-green-500 hover:bg-green-500 hover:text-white px-5 py-3 rounded-xl text-xs font-bold transition-all flex-shrink-0 mt-1 sm:mt-0"><i className="fas fa-check mr-1.5"></i> 標示為已解決</button>
                            </div>
                        ))}
                    </div>
                )}
            </div>
        </div>
    );
}

function PrivacyModal({ onClose, onReadComplete }) {
    const handleScroll = (e) => { const bottom = Math.abs(e.target.scrollHeight - e.target.scrollTop - e.target.clientHeight) < 2; if(bottom && onReadComplete) onReadComplete(); };
    return (<div className="fixed inset-0 z-[200] bg-black/60 backdrop-blur-sm flex flex-col items-center justify-center p-4 animate-fadeIn"><div className="bg-white rounded-3xl p-6 sm:p-8 max-w-sm w-full text-left relative max-h-[85vh] flex flex-col animate-modalPop shadow-2xl"><button onClick={onClose} className="absolute top-4 right-4 w-8 h-8 bg-gray-100 rounded-full flex items-center justify-center text-gray-500 hover:bg-gray-200 transition-colors"><i className="fas fa-times"></i></button><h2 className="text-lg font-black text-gray-900 mb-5 flex-shrink-0 flex items-center gap-2"><i className="fas fa-shield-alt text-blue-500"></i>隱私權與服務條款</h2><div onScroll={handleScroll} className="text-xs text-gray-600 space-y-4 font-medium leading-relaxed overflow-y-auto flex-1 pr-3 scrollbar-hide"><p>歡迎使用 Afitus。保護您的隱私與資料安全是我們的首要承諾，我們採納業界標準技術來守護您的資料：</p><div className="bg-gray-50 p-3 rounded-xl border border-gray-100"><strong className="text-gray-900 block mb-1">1. 資訊蒐集與加密儲存</strong>我們僅收集必要之登入資訊(Email)及您的運動日誌。為保障帳戶安全，您的密碼在傳輸後會立即透過 <span className="text-blue-500 font-bold">bcrypt 強雜湊演算法</span>進行不可逆加密，本平台與任何開發人員皆無法得知或還原您的真實密碼。</div><div className="bg-gray-50 p-3 rounded-xl border border-gray-100"><strong className="text-gray-900 block mb-1">2. 權限控管與防護</strong>本平台導入多層安全防禦：包含防護 XSS(跨站腳本攻擊) 的輸出過濾、防護 CSRF(跨站請求偽造) 的嚴格 Cookie 政策(SameSite/HttpOnly)，以及防護暴力破解密碼的 API 速率限制。非登入狀態下，任何人皆無法讀取伺服器內的任何圖片。</div><div className="bg-gray-50 p-3 rounded-xl border border-gray-100"><strong className="text-gray-900 block mb-1">3. 您的權利 (被遺忘權)</strong>您隨時擁有對自己資料的絕對控制權。當您於設定中執行「刪除帳號」時，系統將觸發資料銷毀程序。除了刪除資料庫關聯外，您上傳的照片亦會被從伺服器硬碟進行「物理抹除 (Unlink)」，不留任何備份，此過程無法復原。</div><div className="bg-gray-50 p-3 rounded-xl border border-gray-100"><strong className="text-gray-900 block mb-1">4. 個人資料使用原則</strong>我們承諾絕對不將您的電子郵件、照片與運動數據出售、交換或租借給任何第三方商業機構。您的資料僅用於為您呈現個人化圖表與社群動態。</div><div className="bg-blue-50 p-3 rounded-xl border border-blue-100 text-blue-800"><strong className="block mb-1"><i className="fas fa-robot mr-1"></i>5. AI 智能功能聲明</strong>本平台使用之 AI 飲食辨識與對話教練功能，其分析結果與營養素估算皆由人工智慧生成，僅供日常紀錄與輔助參考之用，無法取代專業醫療或營養師之診斷建議。</div><div className="text-blue-500 text-center font-black mt-2 pt-2 pb-1 animate-pulse"><i className="fas fa-chevron-down mr-1"></i> 請滑動至最底端以完成閱讀 <i className="fas fa-chevron-down ml-1"></i></div></div><button onClick={() => { if(onReadComplete) onReadComplete(); onClose(); }} className="w-full mt-5 py-3.5 bg-blue-600 text-white font-black rounded-2xl active:scale-95 text-sm shadow-md shadow-blue-200 flex-shrink-0 transition-transform">我已閱讀完畢</button></div></div>);
}
