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

function App() {
    const getInitPostId = () => new URLSearchParams(window.location.search).get('postId');
    
    const [user, setUser] = useState(null); 
    const [isAdmin, setIsAdmin] = useState(false);
    
    const [view, setView] = useState(getInitPostId() ? 'singlePost' : 'feed'); 
    const [targetPostId, setTargetPostId] = useState(getInitPostId());
    
    const [authView, setAuthView] = useState('login');
    const [posts, setPosts] = useState([]); 
    const [comments, setComments] = useState([]);
    const [socialData, setSocialData] = useState({ notifications: [], friends: [] });
    const [loading, setLoading] = useState(true); 
    const [zoomData, setZoomData] = useState(null);
    const [targetEmail, setTargetEmail] = useState(null); 
    const [showSettings, setShowSettings] = useState(false);
    const [showReport, setShowReport] = useState(false); 
    const [showDropdown, setShowDropdown] = useState(false);
    const [showVerifyBanner, setShowVerifyBanner] = useState(false);

    // ⭐ 計時器與選單狀態
    const [showPlusMenu, setShowPlusMenu] = useState(false);
    const [prefilledWorkout, setPrefilledWorkout] = useState([]);

    useEffect(() => {
        secureFetch('/api/admin/check').then(r=>r.json()).then(data => {
            if (data && data.isAdmin) { 
                setIsAdmin(true); 
                setLoading(false); 
            } else { 
                fetchUser(true);
            }
        }).catch(() => setLoading(false));
    },[]);

    const subscribeToPush = async () => {
        if (!('serviceWorker' in navigator) || !('PushManager' in window)) return;
        try {
            const reg = await navigator.serviceWorker.ready;
            const res = await secureFetch('/api/push/public-key').then(r=>r.json());
            const urlBase64ToUint8Array = (b) => { 
                const padding = '='.repeat((4 - b.length % 4) % 4); 
                const base64 = (b + padding).replace(/\-/g, '+').replace(/_/g, '/'); 
                const rawData = window.atob(base64); 
                const outputArray = new Uint8Array(rawData.length); 
                for (let i = 0; i < rawData.length; ++i) outputArray[i] = rawData.charCodeAt(i); 
                return outputArray; 
            };
            const subscription = await reg.pushManager.subscribe({ userVisibleOnly: true, applicationServerKey: urlBase64ToUint8Array(res.publicKey) });
            await secureFetch('/api/push/subscribe', { method: 'POST', headers: {'Content-Type': 'application/json'}, body: JSON.stringify(subscription) });
        } catch (err) {}
    };

    useEffect(() => {
        if (!user) return;
        if (window.Notification && Notification.permission === 'granted') subscribeToPush();
        const interval = setInterval(() => { refreshAll(); }, 15000);
        const handleMessage = (event) => { if (event.data && event.data.type === 'REFRESH_DATA') refreshAll(); };
        if ('serviceWorker' in navigator) navigator.serviceWorker.addEventListener('message', handleMessage);
        return () => { clearInterval(interval); if ('serviceWorker' in navigator) navigator.serviceWorker.removeEventListener('message', handleMessage); };
    }, [user]);

    const fetchUser = (isInitial = false) => {
        secureFetch('/api/me')
            .then(r => r.ok ? r.json() : null)
            .then(u => { 
                if (u && !u.error) { 
                    setUser(u);
                    if (isInitial && !u.isEmailVerified) setShowVerifyBanner(true); 
                    if (isInitial) refreshAll(); 
                } 
                if (isInitial) setLoading(false); 
            })
            .catch(() => { if (isInitial) setLoading(false); });
    };

    const fetchFeed = () => { secureFetch('/api/feed').then(r => r.json()).then(data => { setPosts(data.posts ||[]); setComments(data.comments ||[]); }).catch(()=>{}); };
    const fetchSocialData = () => { secureFetch('/api/notifications_and_friends').then(r=>r.json()).then(data => { if(data && !data.error) setSocialData({ notifications: data.notifications ||[], friends: data.friends ||[] }); }).catch(()=>{}); };
    
    const refreshAll = () => { fetchUser(); fetchFeed(); fetchSocialData(); };
    
    const handleZoom = (imgs, idx) => setZoomData({ images: imgs, index: idx });
    const handleLogout = () => { secureFetch('/api/logout', {method:'POST'}).then(() => { window.location.href = '/'; }); };
    const handleAdminLogout = async () => { try { await secureFetch('/api/admin/logout', { method: 'POST' }); } catch(e){} setIsAdmin(false); window.location.replace('/'); };
    const openTargetProfile = (email) => { if(user && email === user.email) { setView('profile'); } else { setTargetEmail(email); setView('targetProfile'); } };

    const handleAuth = (e, email, password, confirm, nickname, setIsSaving, remember) => {
        e.preventDefault();
        if (authView === 'register' && password !== confirm) return alert('兩次密碼輸入不一致！');
        if (password.length < 8) return alert('密碼請設定至少 8 個字元！');
        setIsSaving(true);
        secureFetch('/api/' + authView, { method: 'POST', headers: {'Content-Type': 'application/json'}, body: JSON.stringify({ email, password, nickname, remember }) })
        .then(async r => { const res = await r.json(); if(!r.ok) throw res; return res; })
        .then(res => { 
            if(authView === 'login') { 
                setUser(res.user); 
                if(!res.user.isEmailVerified) setShowVerifyBanner(true); 
                refreshAll(); 
            } else { 
                alert('註冊成功！請登入'); 
                setAuthView('login'); 
            } 
        })
        .catch(err => {
            alert('錯誤: ' + (err.error || err.message || JSON.stringify(err)));
        }).finally(() => setIsSaving(false));
    };

    if (loading) return <div className="h-screen flex items-center justify-center font-black italic text-blue-600 animate-pulse text-2xl">AFITUS</div>;
    if (isAdmin) return <AdminPanel onLogout={handleAdminLogout} />;
    if (!user) return <AuthPage authView={authView} setAuthView={setAuthView} handleAuth={handleAuth} onAdminLogin={() => setIsAdmin(true)} />;

    return (
        <div className="max-w-md mx-auto h-[100dvh] flex flex-col bg-gray-50 shadow-2xl relative overflow-hidden font-sans">
            {/* ⭐ 全域彈出視窗 */}
            {user.isFirstLogin && <OnboardingModal user={user} onComplete={() => { setUser({...user, isFirstLogin: false}); secureFetch('/api/onboarding/complete', {method:'POST'}); }} />}
            {showSettings && <SettingsModal user={user} setUser={setUser} onClose={() => setShowSettings(false)} refreshAll={refreshAll} />}
            {showReport && <ReportModal onClose={() => setShowReport(false)} />}
            
            {/* 圖片放大檢視 */}
            {zoomData && (
                <div className="fixed inset-0 z-[100] bg-black/95 flex flex-col items-center justify-center animate-fadeIn" onClick={() => setZoomData(null)}>
                     <button className="absolute top-4 right-4 text-white bg-white/10 w-10 h-10 rounded-full flex items-center justify-center z-20"><i className="fas fa-times text-lg"></i></button>
                     <div className="w-full flex-1 flex items-center justify-center p-2 relative" onClick={e => e.stopPropagation()}>
                         <img src={zoomData.images[zoomData.index].startsWith('http') || zoomData.images[zoomData.index].startsWith('data:') ? zoomData.images[zoomData.index] : SERVER_URL + zoomData.images[zoomData.index]} className="max-w-full max-h-[80dvh] object-contain rounded-lg shadow-2xl" />
                         {zoomData.images.length > 1 && (
                             <div className="absolute inset-y-0 w-full flex items-center justify-between px-4 pointer-events-none">
                                <button className={`w-12 h-12 rounded-full bg-black/50 text-white flex items-center justify-center pointer-events-auto backdrop-blur-sm active:scale-90 transition-opacity ${zoomData.index === 0 ? 'opacity-0' : ''}`} onClick={(e) => {e.stopPropagation(); if(zoomData.index > 0) setZoomData({...zoomData, index: zoomData.index-1})}}><i className="fas fa-chevron-left"></i></button>
                                <button className={`w-12 h-12 rounded-full bg-black/50 text-white flex items-center justify-center pointer-events-auto backdrop-blur-sm active:scale-90 transition-opacity ${zoomData.index === zoomData.images.length - 1 ? 'opacity-0' : ''}`} onClick={(e) => {e.stopPropagation(); if(zoomData.index < zoomData.images.length - 1) setZoomData({...zoomData, index: zoomData.index+1})}}><i className="fas fa-chevron-right"></i></button>
                             </div>
                         )}
                     </div>
                     {zoomData.images.length > 1 && <div className="text-white font-bold text-xs pb-4">{zoomData.index + 1} / {zoomData.images.length}</div>}
                </div>
            )}

            {/* 頂部導覽列 */}
            <header className="py-3 px-4 border-b flex justify-between items-center bg-white/95 backdrop-blur-md sticky top-0 z-40 shadow-sm relative">
                <div className="flex items-center gap-1.5 font-black italic text-blue-600 text-xl tracking-tighter cursor-pointer" onClick={() => setView('feed')}><i className="fas fa-fire text-blue-600 text-lg"></i> AFITUS</div>
                <div className="relative">
                    <button onClick={() => setShowDropdown(!showDropdown)} className="w-8 h-8 rounded-full border border-blue-100 overflow-hidden shadow-sm bg-gray-100 flex-shrink-0 flex items-center justify-center transition-transform active:scale-95">
                        {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-user text-gray-400 text-xs"></i>}
                    </button>
                    {showDropdown && (
                        <div>
                            <div className="fixed inset-0 z-40" onClick={() => setShowDropdown(false)}></div>
                            <div className="absolute right-0 mt-2 w-48 bg-white rounded-xl shadow-lg border border-gray-100 overflow-hidden z-50 animate-slideDown">
                                <button onClick={() => { setShowDropdown(false); setShowSettings(true); }} className="w-full text-left px-4 py-3 text-xs font-bold text-gray-600 hover:bg-gray-50 border-b border-gray-50 flex items-center gap-2"><i className="fas fa-cog text-gray-400 w-4 text-center mr-2"></i> 帳戶設定</button>
                                <button onClick={() => { setShowDropdown(false); setShowReport(true); }} className="w-full text-left px-4 py-3 text-xs font-bold text-gray-600 hover:bg-gray-50 border-b border-gray-50 flex items-center gap-2"><i className="fas fa-bug text-gray-400 w-4 text-center mr-2"></i> 回報與建議</button>
                                <button onClick={handleLogout} className="w-full text-left px-4 py-3 text-xs font-bold text-red-500 hover:bg-red-50 flex items-center gap-2"><i className="fas fa-sign-out-alt w-4 text-center mr-2"></i> 登出帳號</button>
                            </div>
                        </div>
                    )}
                </div>
            </header>

            {/* 信箱驗證提示 */}
            {showVerifyBanner && user && !user.isEmailVerified && (
                <div className="bg-yellow-100 border-b border-yellow-200 p-3 flex items-start gap-3 text-yellow-800 animate-slideDown relative z-30">
                    <i className="fas fa-exclamation-triangle mt-1 flex-shrink-0"></i>
                    <div className="flex-1 pr-4">
                        <p className="text-xs font-black">您的電子郵件尚未驗證！</p>
                        <p className="text-[10px] mt-1 leading-relaxed">建議前往「<span className="font-bold underline cursor-pointer" onClick={() => { setShowVerifyBanner(false); setShowSettings(true); }}>設定</span>」完成信箱驗證，以確保帳號安全。</p>
                    </div>
                    <button onClick={() => setShowVerifyBanner(false)} className="w-6 h-6 rounded-full bg-yellow-200/50 hover:bg-yellow-200 text-xs flex-shrink-0 flex items-center justify-center transition-colors">
                        <i className="fas fa-times"></i>
                    </button>
                </div>
            )}

            {/* 主要內容區域 */}
            <main className="flex-1 overflow-y-auto relative bg-gray-50">
                {view === 'singlePost' && <SinglePostView postId={targetPostId} posts={posts} comments={comments} user={user} refreshAll={refreshAll} onZoom={handleZoom} onUserClick={openTargetProfile} onBack={() => { setTargetPostId(null); setView('feed'); window.history.replaceState(null, '', '/'); }} />}
                {view === 'feed' && <Feed posts={posts} comments={comments} user={user} refreshAll={refreshAll} onZoom={handleZoom} onUserClick={openTargetProfile} />}
                {view === 'search' && <SearchFriendsView onUserClick={openTargetProfile} />}
                {/* 發文頁面 (接收計時器傳來的 prefilledWorkout 資料) */}
                {view === 'post' && <PostForm user={user} prefilledWorkout={prefilledWorkout} onSave={() => {refreshAll(); setPrefilledWorkout([]); setView('feed');}} onCancel={() => {setPrefilledWorkout([]); setView('feed');}} />}
                {view === 'notify' && <NotificationsView socialData={socialData} fetchSocialData={fetchSocialData} onUserClick={openTargetProfile} />}
                {view === 'profile' && <ProfileView user={user} posts={posts} comments={comments} refreshAll={refreshAll} onZoom={handleZoom} onUserClick={openTargetProfile} socialData={socialData} />}
                {view === 'targetProfile' && <TargetProfileView targetUserEmail={targetEmail} onBack={() => setView('feed')} user={user} refreshAll={refreshAll} comments={comments} onZoom={handleZoom} socialData={socialData} fetchSocialData={fetchSocialData} />}
                {/* 計時器頁面 */}
                {view === 'restTimer' && <RestTimerView onBack={() => setView('feed')} onSaveToPost={(data) => { setPrefilledWorkout(data); setView('post'); }} />}
            </main>

            <AIChatModal />

            {/* 底部導覽列 */}
            <nav className="fixed bottom-0 w-full max-w-md bg-white border-t border-gray-100 flex justify-between items-center px-4 py-2 z-30 shadow-[0_-10px_20px_rgba(0,0,0,0.02)] pb-safe">
                <button onClick={() => { setView('feed'); window.history.replaceState(null, '', '/'); }} className={`flex flex-col items-center gap-1 w-12 transition-colors ${view === 'feed' ? 'text-blue-600' : 'text-gray-400'}`}><i className="fas fa-home text-lg"></i><span className="text-[8px] font-black">首頁</span></button>
                <button onClick={() => setView('search')} className={`flex flex-col items-center gap-1 w-12 transition-colors ${view === 'search' ? 'text-blue-600' : 'text-gray-400'}`}><i className="fas fa-search text-lg"></i><span className="text-[8px] font-black">搜尋</span></button>
                
                {/* ⭐ 點擊跳出的加號選單 */}
                <div className="relative flex flex-col items-center">
                    {showPlusMenu && (
                        <>
                            <div className="fixed inset-0 z-40" onClick={() => setShowPlusMenu(false)}></div>
                            <div className="absolute bottom-16 -left-12 w-36 bg-white rounded-2xl shadow-2xl border border-gray-100 p-2 animate-slideDown z-50">
                                <button onClick={() => { setView('post'); setShowPlusMenu(false); }} className="w-full text-left px-4 py-3 text-sm font-black text-gray-700 hover:bg-blue-50 rounded-xl transition-colors"><i className="fas fa-pen text-blue-500 mr-2"></i> 發布動態</button>
                                <button onClick={() => { setView('restTimer'); setShowPlusMenu(false); }} className="w-full text-left px-4 py-3 text-sm font-black text-gray-700 hover:bg-orange-50 rounded-xl transition-colors"><i className="fas fa-stopwatch text-orange-500 mr-2"></i> 計時器</button>
                            </div>
                        </>
                    )}
                    <button onClick={() => setShowPlusMenu(!showPlusMenu)} className="bg-blue-600 text-white w-12 h-12 rounded-[1rem] flex items-center justify-center -mt-8 shadow-lg shadow-blue-200 transition-transform active:scale-95 border-4 border-white z-50">
                        <i className={`fas fa-plus text-lg transition-transform duration-300 ${showPlusMenu ? 'rotate-45' : ''}`}></i>
                    </button>
                </div>

                <button onClick={() => setView('notify')} className={`relative flex flex-col items-center gap-1 w-12 transition-colors ${view === 'notify' ? 'text-blue-600' : 'text-gray-400'}`}><i className="fas fa-bell text-lg"></i>{socialData.notifications?.some(n=>n.status==='pending') && <span className="absolute top-0 right-2 w-2 h-2 bg-red-500 rounded-full border border-white"></span>}<span className="text-[8px] font-black">通知</span></button>
                <button onClick={() => setView('profile')} className={`flex flex-col items-center gap-1 w-12 transition-colors ${view === 'profile' ? 'text-blue-600' : 'text-gray-400'}`}><i className="fas fa-user text-lg"></i><span className="text-[8px] font-black">我</span></button>
            </nav>
        </div>
    );
}

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<App />);
