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

const safeCreateObjectURL = (obj) => {
    if (!obj) return '';
    if (typeof obj === 'string') return obj; 
    try {
        return URL.createObjectURL(obj);
    } catch (e) {
        console.error("預覽載入失敗:", e);
        return '';
    }
};

function HistoryChart({ posts, type }) {
    const chartRef = useRef(null); const chartInstance = useRef(null);
    useEffect(() => {
        if (!chartRef.current) return;
        const labels =[]; const data1 = []; const data2 = []; const data3 =[]; const data4 =[];
        for (let i = 6; i >= 0; i--) {
            const d = new Date(); d.setDate(d.getDate() - i); labels.push(`${d.getMonth()+1}/${d.getDate()}`);
            const startOfDay = new Date(d.getFullYear(), d.getMonth(), d.getDate()).getTime();
            const endOfDay = startOfDay + 86400000;
            
            const dayPosts = posts.filter(p => {
                let postTime = p.timestamp;
                if (typeof postTime === 'string') postTime = new Date(postTime.replace(/-/g, '/')).getTime();
                if (typeof postTime === 'number' && postTime < 10000000000) postTime *= 1000;
                if (!postTime || isNaN(postTime)) postTime = Date.now();
                return p.type === type && postTime >= startOfDay && postTime < endOfDay;
            });

            if (type === 'gym') {
                data1.push(dayPosts.reduce((sum, p) => sum + (Number(p.duration)||0), 0));
                data2.push(dayPosts.reduce((sum, p) => sum + (Number(p.calories)||0), 0));
            } else {
                data1.push(dayPosts.reduce((sum, p) => sum + (Number(p.protein)||0), 0));
                data2.push(dayPosts.reduce((sum, p) => sum + (Number(p.carbs)||0), 0));
                data3.push(dayPosts.reduce((sum, p) => sum + (Number(p.fat)||0), 0));
                data4.push(dayPosts.reduce((sum, p) => sum + (Number(p.calories)||0), 0)); 
            }
        }
        if (chartInstance.current) chartInstance.current.destroy();
        const ctx = chartRef.current.getContext('2d');
        const datasets = type === 'gym' ?[
            { label: '運動時間 (分)', data: data1, backgroundColor: 'rgba(249, 115, 22, 0.8)', borderRadius: 4 },
            { label: '消耗熱量 (大卡)', data: data2, backgroundColor: 'rgba(239, 68, 68, 0.8)', borderRadius: 4 }
        ] :[
            { type: 'line', label: '總熱量 (大卡)', data: data4, borderColor: 'rgba(239, 68, 68, 1)', backgroundColor: 'rgba(239, 68, 68, 0.2)', borderWidth: 2, tension: 0.3, yAxisID: 'y1' },
            { type: 'bar', label: '蛋白質 (g)', data: data1, backgroundColor: 'rgba(74, 222, 128, 0.8)', borderRadius: 4, yAxisID: 'y' },
            { type: 'bar', label: '碳水 (g)', data: data2, backgroundColor: 'rgba(96, 165, 250, 0.8)', borderRadius: 4, yAxisID: 'y' },
            { type: 'bar', label: '脂肪 (g)', data: data3, backgroundColor: 'rgba(251, 191, 36, 0.8)', borderRadius: 4, yAxisID: 'y' }
        ];
        chartInstance.current = new window.Chart(ctx, {
            type: 'bar', data: { labels, datasets },
            options: { responsive: true, maintainAspectRatio: false, scales: { y: { beginAtZero: true, position: 'left', border: {display: false} }, y1: { beginAtZero: true, position: 'right', display: type === 'meal', border: {display: false}, grid: { display: false } }, x: { border: {display: false}, grid: { display: false } } }, plugins: { legend: { position: 'bottom', labels: { boxWidth: 10, font: { size: 10, family: 'sans-serif' } } } } }
        });
        return () => { if (chartInstance.current) chartInstance.current.destroy(); };
    },[posts, type]);
    return <div className="h-56 w-full mt-2"><canvas ref={chartRef}></canvas></div>;
}

function MuscleRadarChart({ posts }) {
    const chartRef = useRef(null); const chartInstance = useRef(null);
    useEffect(() => {
        if (!chartRef.current) return;
        const counts = { '胸':0, '背':0, '腿':0, '肩':0, '手':0, '核心':0, '有氧':0 };
        posts.forEach(p => {
            if(p.type === 'gym' && p.content && p.content.includes('===FITSHARE_WORKOUT===')){
                try {
                    const data = JSON.parse(p.content.split('===FITSHARE_WORKOUT===')[1]);
                    data.forEach(ex => { 
                        if(counts[ex.muscle] !== undefined) {
                            counts[ex.muscle] += (ex.sets?.length || 1); 
                        }
                    });
                }catch(e){}
            }
        });
        if (chartInstance.current) chartInstance.current.destroy();
        chartInstance.current = new window.Chart(chartRef.current.getContext('2d'), {
            type: 'radar',
            data: { labels: Object.keys(counts), datasets: [{ label: '累積訓練組數', data: Object.values(counts), backgroundColor: 'rgba(37, 99, 235, 0.2)', borderColor: 'rgba(37, 99, 235, 1)', pointBackgroundColor: 'rgba(37, 99, 235, 1)', borderWidth: 2 }] },
            options: { responsive: true, maintainAspectRatio: false, scales: { r: { angleLines: { color: 'rgba(0,0,0,0.1)' }, grid: { color: 'rgba(0,0,0,0.1)' }, pointLabels: { font: { family: 'sans-serif', size: 11, weight: 'bold' } }, ticks: { display: false } } }, plugins: { legend: { display: false } } }
        });
        return () => { if (chartInstance.current) chartInstance.current.destroy(); };
    },[posts]);
    return <div className="h-56 w-full mt-2"><canvas ref={chartRef}></canvas></div>;
}

function AIChatModal() {
    const [isOpen, setIsOpen] = useState(false);
    const [showMenu, setShowMenu] = useState(false);
    const [mode, setMode] = useState('chat'); 
    
    const [input, setInput] = useState(''); 
    const [loading, setLoading] = useState(false); 
    const [image, setImage] = useState(null);
    const [video, setVideo] = useState(null);
    
    const [actionType, setActionType] = useState('');
    
    const [analysisResult, setAnalysisResult] = useState(null);
    const [messages, setMessages] = useState([{ role: 'model', text: '您好！我是 Afitus AI 智能教教練 💪。想問什麼健身問題呢？' }]);
    
    const chatEndRef = useRef(null); 
    const fileRef = useRef(null);
    const videoRef = useRef(null);

    useEffect(() => { if (mode === 'chat' && chatEndRef.current) chatEndRef.current.scrollIntoView({ behavior: 'smooth' }); }, [messages, loading, isOpen, mode]);

    const handleMenuClick = (selectedMode) => {
        setMode(selectedMode);
        setShowMenu(false);
        setIsOpen(true);
        setAnalysisResult(null); 
        setImage(null);
        setVideo(null);
        setActionType(''); 
        
        if (selectedMode === 'chat') {
            setMessages([{ role: 'model', text: '您好！我是 Afitus AI 智能教練 💪。想問什麼健身問題呢？' }]);
        }
    };

    const handleVideoSelect = (e) => {
        const file = e.target.files[0];
        if (!file) return;
        
        if (file.size > 50 * 1024 * 1024) {
            alert('影片檔案過大 (超過 50MB)！請降低畫質或確保長度在 10 秒以內。');
            e.target.value = '';
            return;
        }
        
        try {
            const videoElement = document.createElement('video');
            videoElement.preload = 'metadata';
            videoElement.onloadedmetadata = function() {
                window.URL.revokeObjectURL(videoElement.src);
                if (videoElement.duration > 11) { 
                    alert(`影片長度為 ${Math.round(videoElement.duration)} 秒，超過 10 秒限制！請重新剪輯後上傳。`);
                    e.target.value = '';
                    setVideo(null);
                } else {
                    setVideo(file); 
                    setAnalysisResult(null); 
                }
            }
            videoElement.src = safeCreateObjectURL(file);
        } catch (err) {
            alert("無法讀取影片，請嘗試其他檔案。");
            e.target.value = '';
        }
    };

    const handleImageSelect = (e) => {
        const file = e.target.files[0];
        if (!file) return;
        setImage(file); 
        setAnalysisResult(null); 
    };

    const handleAnalyzeVideo = async () => {
        if (!video) return;
        setLoading(true);
        setAnalysisResult(null);
        const fd = new FormData(); 
        fd.append('video', video);
        fd.append('actionType', actionType.trim() || '自動偵測'); 
        
        try { 
            const res = await secureFetch('/api/ai/analyze-video', { method: 'POST', body: fd }); 
            if (!res.ok) throw new Error(res.status === 413 ? '影片檔案太大了！請剪輯或壓縮後再上傳。' : '伺服器連線失敗');
            const data = await res.json(); 
            if (data.error) throw new Error(data.error);
            
            setAnalysisResult({ 
                type: 'video', 
                data: data,
                videoUrl: safeCreateObjectURL(video) 
            });
        } catch(e) { 
            alert(e.message || '影片分析失敗，請稍後再試！');
            setVideo(null);
        } finally { 
            setLoading(false); 
            if (videoRef.current) videoRef.current.value = '';
        }
    };

    const handleAnalyzeFood = async () => {
        if (!image) return;
        setLoading(true);
        setAnalysisResult(null);
        const fd = new FormData(); fd.append('image', image);
        
        try { 
            const res = await secureFetch('/api/ai/recognize-food', { method: 'POST', body: fd }); 
            if (!res.ok) throw new Error(res.status === 413 ? '照片檔案太大了！請壓縮後再上傳。' : '伺服器連線失敗');
            const data = await res.json(); 
            if (data.error) throw new Error(data.error);
            setAnalysisResult({ type: 'food', data: data, imageUrl: safeCreateObjectURL(image) });
        } catch(e) { 
            alert(e.message || '食物辨識失敗，請換一張照片試試看！');
            setImage(null);
        } finally { 
            setLoading(false); 
            if (fileRef.current) fileRef.current.value = '';
        }
    };

    const handleSendChat = async () => {
        if (!input.trim() && !image) return;
        const imageUrl = safeCreateObjectURL(image);
        setMessages(prev =>[...prev, { role: 'user', text: input, image: imageUrl }]);
        setInput(''); setLoading(true);
        const fd = new FormData(); fd.append('message', input); if (image) fd.append('image', image); fd.append('history', JSON.stringify(messages.map(m => ({ role: m.role, text: m.text })).slice(-5)));
        try { 
            const res = await secureFetch('/api/ai/chat', { method: 'POST', body: fd }); 
            if (!res.ok) throw new Error(res.status === 413 ? '照片檔案太大了！請壓縮後再上傳。' : '伺服器連線失敗');
            const data = await res.json(); 
            setMessages(prev => [...prev, { role: 'model', text: data.reply || data.error }]); 
        } catch(e) { 
            setMessages(prev =>[...prev, { role: 'model', text: e.message }]); 
        } finally { 
            setLoading(false); setImage(null); if (fileRef.current) fileRef.current.value = '';
        }
    };

    const renderVideoReport = (result) => {
        if (!result || result.type !== 'video') return null;
        const { action, rating, warning, pros, cons, encouragement } = result.data;
        
        const ratingColor = rating === 'A' ? 'text-green-500' : rating === 'B' ? 'text-blue-500' : rating === 'C' ? 'text-yellow-500' : 'text-red-500';
        const ratingBg = rating === 'A' ? 'bg-green-50 border-green-200' : rating === 'B' ? 'bg-blue-50 border-blue-200' : rating === 'C' ? 'bg-yellow-50 border-yellow-200' : 'bg-red-50 border-red-200';

        return (
            <div className="bg-white rounded-2xl shadow-lg border border-gray-100 overflow-hidden animate-fadeIn w-full max-w-sm mx-auto mt-2">
                <div className="bg-purple-600 text-white p-4 flex justify-between items-center">
                    <div className="font-black flex items-center gap-2"><i className="fas fa-video"></i> 動作分析報告</div>
                    <div className="text-xs bg-purple-800 px-2 py-1 rounded-lg text-purple-100">Afitus Vision</div>
                </div>
                
                {result.videoUrl && (
                    <div className="w-full bg-black relative">
                        <video src={result.videoUrl} controls playsInline className="w-full max-h-64 object-contain" />
                        <div className="absolute top-2 left-2 bg-black/50 text-white text-[10px] px-2 py-1 rounded backdrop-blur-sm">
                            <i className="fas fa-play-circle mr-1"></i> 您的原影片
                        </div>
                    </div>
                )}
                
                <div className="p-5 space-y-4">
                    <div className="flex justify-between items-center border-b border-gray-100 pb-4">
                        <div>
                            <div className="text-[10px] font-bold text-gray-400 uppercase tracking-wider mb-1">辨識動作</div>
                            <div className="text-xl font-black text-gray-800">{action || '未知動作'}</div>
                        </div>
                        <div className={`flex flex-col items-center justify-center w-16 h-16 rounded-2xl border-2 ${ratingBg} shadow-sm`}>
                            <span className="text-[10px] font-bold text-gray-500 mb-[-4px]">評分</span>
                            <span className={`text-3xl font-black ${ratingColor}`}>{rating || '?'}</span>
                        </div>
                    </div>

                    {warning && (
                        <div className="bg-red-50 border border-red-200 p-3 rounded-xl flex gap-3 items-start shadow-sm">
                            <i className="fas fa-exclamation-triangle text-red-500 mt-0.5"></i>
                            <div>
                                <div className="text-xs font-black text-red-700 mb-1">安全警示</div>
                                <div className="text-xs text-red-600 font-medium leading-relaxed">{warning}</div>
                            </div>
                        </div>
                    )}

                    <div className="grid grid-cols-1 gap-3">
                        <div className="bg-green-50/50 border border-green-100 p-3 rounded-xl">
                            <div className="text-xs font-black text-green-600 flex items-center gap-1.5 mb-2"><i className="fas fa-check-circle"></i> 動作優點</div>
                            <ul className="space-y-1.5">
                                {pros && pros.length > 0 ? pros.map((p, i) => <li key={i} className="text-xs text-gray-700 font-medium flex items-start gap-2"><span className="text-green-500 mt-0.5">•</span> {p}</li>) : <li className="text-xs text-gray-400">無特別標記</li>}
                            </ul>
                        </div>
                        
                        <div className="bg-orange-50/50 border border-orange-100 p-3 rounded-xl">
                            <div className="text-xs font-black text-orange-600 flex items-center gap-1.5 mb-2"><i className="fas fa-tools"></i> 需要改進</div>
                            <ul className="space-y-2">
                                {cons && cons.length > 0 ? cons.map((c, i) => {
                                    const match = c.match(/(\d+:\d+)/);
                                    const timeTag = match ? match[1] : null;
                                    const text = match ? c.replace(match[0], '').replace(/秒處|秒/g, '').trim() : c;
                                    return (
                                        <li key={i} className="text-xs text-gray-700 font-medium flex items-start gap-2 bg-white p-2 rounded-lg border border-orange-100 shadow-sm">
                                            {timeTag && <span className="bg-orange-100 text-orange-600 px-1.5 py-0.5 rounded text-[10px] font-black flex-shrink-0">{timeTag}</span>}
                                            <span>{text}</span>
                                        </li>
                                    );
                                }) : <li className="text-xs text-gray-400">動作很標準！</li>}
                            </ul>
                        </div>
                    </div>

                    <div className="bg-blue-50 p-3 rounded-xl border border-blue-100 text-center mt-2">
                        <div className="text-xs font-bold text-blue-800 italic">"{encouragement || '繼續保持，下次會更好！'}"</div>
                    </div>

                    <div className="text-[9px] text-gray-400 mt-4 text-center leading-relaxed border-t border-gray-100 pt-3">
                        *AI 教練僅供參考，若偵測結果與體感不符，請以專業教練指導為主。建議調整拍攝角度後再次嘗試。
                    </div>
                </div>
            </div>
        );
    };

    const renderFoodReport = (result) => {
        if (!result || result.type !== 'food') return null;
        const { foodName, calories, protein, carbs, fat, sugar, sodium } = result.data;
        
        return (
            <div className="bg-white rounded-xl shadow-lg border border-gray-200 overflow-hidden animate-fadeIn w-full max-w-sm mx-auto mt-2">
                {result.imageUrl && <img src={result.imageUrl} className="w-full h-40 object-cover" />}
                
                <div className="p-5 bg-white">
                    <div className="border-b-4 border-black pb-1 mb-2">
                        <h2 className="text-2xl font-black text-black tracking-widest">營養標示</h2>
                        <div className="text-base font-bold text-gray-800 mt-1">{foodName || '未知食物'}</div>
                        <div className="text-xs text-gray-500 mt-1">每一份量 1 份 (AI 視覺估算)</div>
                    </div>
                    
                    <div className="flex justify-between items-end border-b border-black py-1">
                        <span className="text-sm font-black">本包裝含</span>
                        <span className="text-sm font-black">1 份</span>
                    </div>
                    
                    <div className="flex justify-between items-end border-b-4 border-black py-1 mt-2">
                        <span className="text-sm font-bold">每份</span>
                    </div>

                    <div className="space-y-0 mt-1">
                        <div className="flex justify-between py-2 border-b border-gray-300">
                            <span className="text-base font-black">熱量</span>
                            <span className="text-base font-black">{calories || 0} 大卡</span>
                        </div>
                        <div className="flex justify-between py-2 border-b border-gray-300">
                            <span className="text-sm font-black">蛋白質</span>
                            <span className="text-sm font-black">{protein || 0} 公克</span>
                        </div>
                        <div className="flex justify-between py-2 border-b border-gray-300">
                            <span className="text-sm font-black">脂肪</span>
                            <span className="text-sm font-black">{fat || 0} 公克</span>
                        </div>
                        <div className="flex justify-between py-2 border-b border-gray-300">
                            <span className="text-sm font-black">碳水化合物</span>
                            <span className="text-sm font-black">{carbs || 0} 公克</span>
                        </div>
                        <div className="flex justify-between py-1.5 border-b border-gray-300 pl-4">
                            <span className="text-sm font-medium text-gray-600">糖</span>
                            <span className="text-sm font-medium text-gray-600">{sugar || 0} 公克</span>
                        </div>
                        <div className="flex justify-between py-2 border-b-4 border-black">
                            <span className="text-sm font-black">鈉</span>
                            <span className="text-sm font-black">{sodium || 0} 毫克</span>
                        </div>
                    </div>
                    
                    <div className="text-[10px] text-gray-400 mt-4 text-center leading-relaxed">
                        *此數值由 Afitus AI 視覺模型估算，僅供日常紀錄參考，實際數值可能因烹調方式與份量有所誤差。
                    </div>
                </div>
            </div>
        );
    };

    const headerConfig = {
        chat: { bg: 'from-blue-600 to-indigo-600', title: '智能對話', icon: 'fa-comment-dots' },
        video: { bg: 'from-purple-600 to-pink-600', title: '動作分析', icon: 'fa-video' },
        food: { bg: 'from-green-500 to-emerald-600', title: '營養辨識', icon: 'fa-utensils' }
    };

    return (
        <>
            <div className="fixed bottom-20 right-4 z-40 flex flex-col-reverse items-end gap-3">
                <button 
                    onClick={() => setShowMenu(!showMenu)} 
                    className="w-14 h-14 bg-gradient-to-tr from-blue-600 to-indigo-600 rounded-full shadow-[0_10px_25px_rgba(37,99,235,0.4)] flex justify-center items-center active:scale-95 transition-transform text-white text-2xl"
                >
                    <i className={showMenu ? "fas fa-times" : "fas fa-robot"}></i>
                </button>

                {showMenu && (
                    <div className="flex flex-col gap-2 animate-slideDown origin-bottom-right mb-2 items-end">
                        <button onClick={() => handleMenuClick('video')} className="flex items-center gap-3 bg-white px-4 py-3 rounded-2xl shadow-lg border border-gray-100 active:scale-95 transition-transform">
                            <div className="text-right"><div className="text-sm font-black text-gray-800">動作分析</div><div className="text-[10px] text-gray-500 font-bold">上傳10秒影片評分</div></div>
                            <div className="w-8 h-8 rounded-full bg-purple-100 text-purple-600 flex items-center justify-center"><i className="fas fa-video"></i></div>
                        </button>
                        <button onClick={() => handleMenuClick('food')} className="flex items-center gap-3 bg-white px-4 py-3 rounded-2xl shadow-lg border border-gray-100 active:scale-95 transition-transform">
                            <div className="text-right"><div className="text-sm font-black text-gray-800">營養辨識</div><div className="text-[10px] text-gray-500 font-bold">拍照產生營養標示</div></div>
                            <div className="w-8 h-8 rounded-full bg-green-100 text-green-600 flex items-center justify-center"><i className="fas fa-utensils"></i></div>
                        </button>
                        <button onClick={() => handleMenuClick('chat')} className="flex items-center gap-3 bg-white px-4 py-3 rounded-2xl shadow-lg border border-gray-100 active:scale-95 transition-transform">
                            <div className="text-right"><div className="text-sm font-black text-gray-800">智能對話</div><div className="text-[10px] text-gray-500 font-bold">隨時解答健身疑問</div></div>
                            <div className="w-8 h-8 rounded-full bg-blue-100 text-blue-600 flex items-center justify-center"><i className="fas fa-comment-dots"></i></div>
                        </button>
                    </div>
                )}
            </div>

            {isOpen && (
                <div className="fixed inset-0 z-50 flex flex-col bg-white sm:rounded-t-3xl sm:top-20 animate-slideDown overflow-hidden shadow-2xl">
                    <div className={`bg-gradient-to-r ${headerConfig[mode].bg} p-4 flex justify-between text-white shadow-md z-10`}>
                        <div className="flex items-center gap-3">
                            <div className="w-10 h-10 rounded-full bg-white/20 border-2 overflow-hidden flex items-center justify-center text-xl">
                                {mode === 'chat' ? <img src="https://api.dicebear.com/7.x/bottts/svg?seed=AfitusAI" className="w-full h-full object-cover"/> : <i className={`fas ${headerConfig[mode].icon}`}></i>}
                            </div>
                            <div>
                                <div className="font-black">Afitus AI <span className="text-[10px] bg-white/20 px-2 py-0.5 rounded-full ml-1">{headerConfig[mode].title}</span></div>
                                <div className="text-[10px] text-white/80 flex items-center gap-1"><span className="w-1.5 h-1.5 rounded-full bg-green-400 animate-pulse"></span> 系統就緒</div>
                            </div>
                        </div>
                        <button onClick={() => setIsOpen(false)} className="w-8 h-8 rounded-full bg-white/10 hover:bg-white/20"><i className="fas fa-chevron-down"></i></button>
                    </div>
                    
                    <div className="flex-1 overflow-y-auto p-4 bg-gray-50">
                        {mode === 'chat' && (
                            <div className="space-y-4 pb-4">
                                {messages.map((msg, i) => (
                                    <div key={i} className={`flex ${msg.role === 'user' ? 'justify-end' : 'justify-start'}`}>
                                        <div className={`max-w-[85%] rounded-2xl p-3 text-sm shadow-sm ${msg.role === 'user' ? 'bg-blue-600 text-white rounded-tr-sm' : 'bg-white border text-gray-800 rounded-tl-sm'}`}>
                                            {msg.image && <img src={msg.image} className="w-full rounded-xl mb-2 object-cover max-h-48" />}
                                            <div className="whitespace-pre-wrap leading-relaxed font-medium">{msg.text}</div>
                                        </div>
                                    </div>
                                ))}
                                {loading && (
                                    <div className="flex justify-start">
                                        <div className="bg-white border rounded-2xl rounded-tl-sm p-4 shadow-sm text-blue-600 flex items-center gap-2">
                                            <i className="fas fa-circle-notch fa-spin text-lg"></i>
                                            <span className="text-xs font-bold text-gray-500">教練正在思考...</span>
                                        </div>
                                    </div>
                                )}
                                <div ref={chatEndRef} />
                            </div>
                        )}

                        {mode === 'video' && (
                            <div className="h-full flex flex-col">
                                {!video && !analysisResult && !loading && (
                                    <div className="flex-1 flex flex-col items-center justify-center">
                                        <div onClick={() => videoRef.current.click()} className="w-full max-w-xs border-2 border-dashed border-purple-300 bg-purple-50 hover:bg-purple-100 rounded-3xl p-8 text-center cursor-pointer transition-colors shadow-sm">
                                            <div className="w-16 h-16 bg-purple-200 text-purple-600 rounded-full flex items-center justify-center mx-auto mb-4 text-2xl shadow-inner"><i className="fas fa-cloud-upload-alt"></i></div>
                                            <h3 className="text-lg font-black text-purple-800 mb-2">上傳健身影片</h3>
                                            <p className="text-xs text-purple-600/80 font-bold leading-relaxed">支援 MP4/MOV 格式<br/>長度請限制在 10 秒以內</p>
                                        </div>
                                        
                                        <div className="mt-6 bg-white p-4 rounded-2xl border border-gray-100 shadow-sm w-full max-w-xs text-left">
                                            <div className="text-xs font-black text-gray-700 mb-2"><i className="fas fa-info-circle text-blue-500 mr-1"></i> 拍攝指南</div>
                                            <ul className="text-[10px] text-gray-500 space-y-1.5 font-medium">
                                                <li>• 建議側拍 45 度角，確保全身入鏡。</li>
                                                <li>• 穿著合身衣物，避免過度寬鬆遮擋關節。</li>
                                                <li>• 確保光線充足，避免背光拍攝。</li>
                                            </ul>
                                        </div>
                                        
                                        <input type="file" hidden ref={videoRef} accept="video/mp4,video/quicktime,video/x-m4v,video/*" onChange={handleVideoSelect} />
                                    </div>
                                )}

                                {video && !loading && !analysisResult && (
                                    <div className="flex-1 flex flex-col items-center justify-center w-full max-w-xs mx-auto">
                                        <div className="w-full bg-white border border-purple-100 rounded-2xl p-6 text-center shadow-sm mb-6">
                                            <div className="w-16 h-16 bg-purple-100 text-purple-600 rounded-full flex items-center justify-center mx-auto mb-3 text-2xl"><i className="fas fa-video"></i></div>
                                            <h3 className="font-black text-gray-800 mb-1">影片已就緒</h3>
                                            <p className="text-xs text-gray-500 font-bold break-all px-4">{video.name}</p>
                                        </div>
                                        
                                        <div className="w-full mb-6">
                                            <label className="text-xs font-black text-gray-600 mb-2 block">請輸入動作名稱 (幫助 AI 更精準)</label>
                                            <input 
                                                type="text"
                                                value={actionType} 
                                                onChange={(e) => setActionType(e.target.value)}
                                                placeholder="例如：深蹲、臥推 (留空則自動偵測)"
                                                className="w-full bg-white border border-gray-200 rounded-xl p-3 text-sm font-bold text-gray-700 outline-none focus:border-purple-400 shadow-sm"
                                            />
                                        </div>

                                        <button onClick={handleAnalyzeVideo} className="w-full bg-purple-600 text-white py-4 rounded-2xl font-black shadow-lg shadow-purple-200 active:scale-95 transition-transform text-lg">開始 AI 分析</button>
                                        <button onClick={() => setVideo(null)} className="w-full mt-4 py-3 text-gray-400 font-bold text-sm hover:text-gray-600">重新選擇影片</button>
                                    </div>
                                )}

                                {loading && (
                                    <div className="flex-1 flex flex-col items-center justify-center">
                                        <div className="w-20 h-20 bg-white rounded-2xl shadow-lg flex items-center justify-center mb-4 border border-gray-100">
                                            <i className="fas fa-circle-notch fa-spin text-4xl text-purple-600"></i>
                                        </div>
                                        <h3 className="font-black text-gray-800">AI 正在仔細分析動作軌跡</h3>
                                        <p className="text-xs text-gray-500 mt-2 font-bold">這可能需要幾秒鐘的時間...</p>
                                    </div>
                                )}

                                {analysisResult && (
                                    <div className="pb-6">
                                        {renderVideoReport(analysisResult)}
                                        <button onClick={() => {setAnalysisResult(null); setVideo(null); setActionType('');}} className="w-full max-w-sm mx-auto block mt-6 py-4 bg-gray-900 text-white rounded-2xl font-black shadow-lg active:scale-95 transition-transform">分析其他影片</button>
                                    </div>
                                )}
                            </div>
                        )}

                        {mode === 'food' && (
                            <div className="h-full flex flex-col">
                                {!image && !analysisResult && !loading && (
                                    <div className="flex-1 flex flex-col items-center justify-center">
                                        <div onClick={() => fileRef.current.click()} className="w-full max-w-xs border-2 border-dashed border-green-300 bg-green-50 hover:bg-green-100 rounded-3xl p-8 text-center cursor-pointer transition-colors shadow-sm">
                                            <div className="w-16 h-16 bg-green-200 text-green-600 rounded-full flex items-center justify-center mx-auto mb-4 text-2xl shadow-inner"><i className="fas fa-camera"></i></div>
                                            <h3 className="text-lg font-black text-green-800 mb-2">拍攝或上傳食物</h3>
                                            <p className="text-xs text-green-600/80 font-bold leading-relaxed">AI 將自動為您產生<br/>標準營養標示卡</p>
                                        </div>
                                        <input type="file" hidden ref={fileRef} accept="image/*" onChange={handleImageSelect} />
                                    </div>
                                )}

                                {image && !loading && !analysisResult && (
                                    <div className="flex-1 flex flex-col items-center justify-center w-full max-w-xs mx-auto">
                                        <div className="w-full bg-white border border-green-100 rounded-2xl p-2 text-center shadow-sm mb-6">
                                            <img src={safeCreateObjectURL(image)} className="w-full h-48 object-cover rounded-xl" />
                                        </div>
                                        <button onClick={handleAnalyzeFood} className="w-full bg-green-600 text-white py-4 rounded-2xl font-black shadow-lg shadow-green-200 active:scale-95 transition-transform text-lg">產生營養標示</button>
                                        <button onClick={() => setImage(null)} className="w-full mt-4 py-3 text-gray-400 font-bold text-sm hover:text-gray-600">重新選擇照片</button>
                                    </div>
                                )}

                                {loading && (
                                    <div className="flex-1 flex flex-col items-center justify-center">
                                        <div className="w-20 h-20 bg-white rounded-2xl shadow-lg flex items-center justify-center mb-4 border border-gray-100">
                                            <i className="fas fa-circle-notch fa-spin text-4xl text-green-600"></i>
                                        </div>
                                        <h3 className="font-black text-gray-800">AI 正在計算營養素</h3>
                                        <p className="text-xs text-gray-500 mt-2 font-bold">正在辨識食物種類與份量...</p>
                                    </div>
                                )}

                                {analysisResult && (
                                    <div className="pb-6">
                                        {renderFoodReport(analysisResult)}
                                        <button onClick={() => {setAnalysisResult(null); setImage(null);}} className="w-full max-w-sm mx-auto block mt-6 py-4 bg-gray-900 text-white rounded-2xl font-black shadow-lg active:scale-95 transition-transform">辨識其他食物</button>
                                    </div>
                                )}
                            </div>
                        )}
                    </div>
                    
                    {mode === 'chat' && (
                        <div className="p-3 bg-white border-t flex items-end gap-2 relative">
                            {image && (
                                <div className="absolute -top-16 left-4 bg-white border p-1 rounded-xl shadow-lg flex items-center gap-2">
                                    <img src={safeCreateObjectURL(image)} className="w-10 h-10 object-cover rounded-lg" />
                                    <button onClick={() => setImage(null)} className="w-5 h-5 bg-gray-200 rounded-full text-[10px]"><i className="fas fa-times"></i></button>
                                </div>
                            )}
                            
                            <button onClick={() => fileRef.current.click()} className="w-10 h-10 rounded-full bg-gray-100 flex items-center justify-center text-gray-500 flex-shrink-0 hover:bg-gray-200 active:scale-95"><i className="fas fa-image"></i></button>
                            <input type="file" hidden ref={fileRef} accept="image/*" onChange={handleImageSelect} />

                            <textarea 
                                value={input} 
                                onChange={e => setInput(e.target.value)} 
                                onKeyDown={e => { if(e.key==='Enter' && !e.shiftKey) { e.preventDefault(); handleSendChat(); } }} 
                                placeholder="問教練問題或傳照片..." 
                                className="flex-1 max-h-32 min-h-[40px] bg-gray-100 rounded-2xl px-4 py-2.5 text-sm outline-none resize-none scrollbar-hide shadow-inner" 
                                rows="1" 
                            />
                            
                            <button onClick={handleSendChat} disabled={loading || (!input.trim() && !image)} className="w-10 h-10 rounded-full bg-blue-600 text-white flex-shrink-0 disabled:opacity-50 shadow-md active:scale-95 transition-transform"><i className="fas fa-paper-plane"></i></button>
                        </div>
                    )}
                </div>
            )}
        </>
    );
}

// ⭐ 接收計時器傳來的 prefilledWorkout 資料，並自動載入
function PostForm({ user, onSave, onCancel, prefilledWorkout }) {
    const [type, setType] = useState('post'); 
    const [privacy, setPrivacy] = useState('public');
    const [content, setContent] = useState(''); 
    const [images, setImages] = useState([]);
    const [duration, setDuration] = useState(''); 
    const [calories, setCalories] = useState('');
    const [protein, setProtein] = useState(''); 
    const [carbs, setCarbs] = useState(''); 
    const [fat, setFat] = useState('');
    const [busy, setBusy] = useState(false); 
    const [aiRec, setAiRec] = useState(false);
    const aiFileRef = useRef(null); 
    const generalFileRef = useRef(null);

    const [routines, setRoutines] = useState([]);
    const [workoutExercises, setWorkoutExercises] = useState([]); 
    const [exSearch, setExSearch] = useState('');
    const [showExList, setShowExList] = useState(false);
    const [customMuscle, setCustomMuscle] = useState('其他');

    // ⭐ 如果有傳入計時器的資料，自動將分類設定為 gym 並帶入資料
    useEffect(() => {
        if (prefilledWorkout && prefilledWorkout.length > 0) {
            setType('gym');
            setWorkoutExercises(prefilledWorkout);
        }
    }, [prefilledWorkout]);

    useEffect(() => {
        secureFetch('/api/me')
            .then(res => res.ok ? res.json() : null)
            .then(liveUser => {
                if (liveUser && liveUser.routines) {
                    setRoutines(liveUser.routines);
                } else if (user && user.routines) {
                    setRoutines(user.routines);
                }
            })
            .catch(() => {});
    }, [user]);

    const loadRoutine = (id) => {
        const r = routines.find(x => x.id === id);
        if (r && r.exercises) setWorkoutExercises(JSON.parse(JSON.stringify(r.exercises))); 
    };

    const addExercise = (name, isCustom = false, muscle = '其他') => {
        if(!name.trim()) return;
        setWorkoutExercises([...workoutExercises, { name, muscle: isCustom ? customMuscle : muscle, sets: [{ weight: '', reps: '' }] }]);
        setExSearch('');
        setShowExList(false);
        setCustomMuscle('其他'); 
    };

    const updateSet = (exIdx, setIdx, field, val) => {
        const newW = [...workoutExercises]; newW[exIdx].sets[setIdx][field] = val; setWorkoutExercises(newW);
    };

    const addSet = (exIdx) => {
        const newW = [...workoutExercises]; newW[exIdx].sets.push({ weight: '', reps: '' }); setWorkoutExercises(newW);
    };

    const removeExercise = (exIdx) => {
        setWorkoutExercises(workoutExercises.filter((_, i) => i !== exIdx));
    };

    const handleFile = (e) => { setImages([...images, ...Array.from(e.target.files).slice(0, 5 - images.length)]); };
    
    const handleAIPredict = async (e) => {
        const file = e.target.files[0]; 
        if (!file) return;
        
        setAiRec(true); 
        const fd = new FormData(); 
        fd.append('image', file);
        
        try {
            const res = await secureFetch('/api/ai/recognize-food', { method: 'POST', body: fd });
            if (!res.ok) throw new Error(res.status === 413 ? '照片檔案太大了！請壓縮後再上傳。' : '伺服器連線失敗');
            const data = await res.json(); 
            if (data.error) throw new Error(data.error);
            
            setContent(data.foodName ? `【Afitus AI辨識】\n我吃了：${data.foodName}\n\n${content}` : content);
            setCalories(data.calories||0); setProtein(data.protein||0); setCarbs(data.carbs||0); setFat(data.fat||0);
            if (images.length<5) setImages([...images, file]);
            alert('✨ AI 辨識完成！');
        } catch (err) { 
            alert('AI 辨識失敗：' + err.message); 
        } finally { 
            setAiRec(false); 
            if (aiFileRef.current) aiFileRef.current.value = ''; 
        }
    };

    const submit = async () => {
        if (!content.trim() && images.length === 0 && workoutExercises.length === 0) return alert('請輸入內容或動作');
        setBusy(true); 
        
        let finalContent = content;
        if (type === 'gym' && workoutExercises.length > 0) {
            let workoutText = '💪 【今日訓練紀錄】\n';
            workoutExercises.forEach(ex => {
                const setsText = ex.sets.map(s => `${s.weight||0}kg x ${s.reps||0}`).join(', ');
                workoutText += `🔸 ${ex.name}: ${setsText}\n`;
            });
            finalContent = workoutText + '\n' + content + `\n\n===FITSHARE_WORKOUT===${JSON.stringify(workoutExercises)}`;
        }

        const fd = new FormData(); fd.append('content', finalContent); fd.append('type', type); fd.append('privacy', privacy);
        fd.append('duration', duration||0); fd.append('calories', calories||0); fd.append('protein', protein||0); fd.append('carbs', carbs||0); fd.append('fat', fat||0);
        images.forEach(img => fd.append('images', img));
        secureFetch('/api/posts', { method: 'POST', body: fd }).then(() => onSave()).catch(() => { setBusy(false); alert('發佈失敗'); });
    };

    return (
        <div className="p-5 animate-fadeIn pb-24 h-full overflow-y-auto relative bg-white">
            <div className="flex justify-between items-center mb-6"><h2 className="text-xl font-black text-gray-800">發佈動態</h2><button onClick={onCancel} className="w-8 h-8 rounded-full bg-gray-100"><i className="fas fa-times"></i></button></div>
            
            <div className="flex bg-gray-100 p-1 rounded-xl mb-3 shadow-inner">
                <button className={`flex-1 py-2 text-xs font-bold rounded-lg transition-colors ${type === 'post' ? 'text-blue-600 bg-white shadow-sm' : 'text-gray-500'}`} onClick={() => setType('post')}>一般</button>
                <button className={`flex-1 py-2 text-xs font-bold rounded-lg transition-colors ${type === 'gym' ? 'text-orange-600 bg-white shadow-sm' : 'text-gray-500'}`} onClick={() => setType('gym')}>健身</button>
                <button className={`flex-1 py-2 text-xs font-bold rounded-lg transition-colors ${type === 'meal' ? 'text-green-600 bg-white shadow-sm' : 'text-gray-500'}`} onClick={() => setType('meal')}>飲食</button>
            </div>
            
            <div className="mb-5 flex bg-gray-100 p-1 rounded-xl shadow-inner relative">
                <button className={`flex-1 py-2 text-xs font-bold rounded-lg transition-colors ${privacy === 'public' ? 'text-gray-800 shadow-sm bg-white' : 'text-gray-500'}`} onClick={() => setPrivacy('public')}><i className="fas fa-globe"></i> 公開</button>
                <button className={`flex-1 py-2 text-xs font-bold rounded-lg transition-colors ${privacy === 'friends' ? 'text-gray-800 shadow-sm bg-white' : 'text-gray-500'}`} onClick={() => setPrivacy('friends')}><i className="fas fa-user-friends"></i> 好友</button>
                <button className={`flex-1 py-2 text-xs font-bold rounded-lg transition-colors ${privacy === 'private' ? 'text-gray-800 shadow-sm bg-white' : 'text-gray-500'}`} onClick={() => setPrivacy('private')}><i className="fas fa-lock"></i> 私人</button>
            </div>

            {type === 'gym' && (
                <div className="mb-5 bg-orange-50/50 p-4 rounded-2xl border border-orange-100 relative">
                    <h3 className="text-xs font-black text-orange-600 mb-3"><i className="fas fa-dumbbell"></i> 訓練動作紀錄</h3>

                    {routines.length > 0 && (
                        <div className="mb-4">
                            <select onChange={e => { if(e.target.value) loadRoutine(e.target.value); e.target.value=''; }} className="w-full bg-white border border-orange-200 rounded-xl p-2.5 text-sm font-bold text-orange-700 outline-none shadow-sm cursor-pointer">
                                <option value="">⚡ 快速載入我的菜單...</option>
                                {routines.map(r => <option key={r.id} value={r.id}>{r.name}</option>)}
                            </select>
                        </div>
                    )}

                    <div className="space-y-3 mb-4 max-h-64 overflow-y-auto pr-1">
                        {workoutExercises.map((ex, exIdx) => (
                            <div key={exIdx} className="bg-white p-3 rounded-xl shadow-sm border border-gray-100 relative">
                                <div className="font-black text-sm text-gray-800 mb-2 pr-6">{ex.name} <span className="text-[10px] text-gray-400 font-normal ml-1">({ex.muscle})</span></div>
                                <button onClick={() => removeExercise(exIdx)} className="absolute top-3 right-3 text-red-400 hover:text-red-600"><i className="fas fa-times"></i></button>
                                {ex.sets.map((s, sIdx) => (
                                    <div key={sIdx} className="flex flex-wrap gap-2 mb-2 items-center">
                                        <span className="text-[10px] font-bold text-gray-400 w-8 flex-shrink-0">第{sIdx+1}組</span>
                                        <input type="number" placeholder="重量(kg)" value={s.weight} onChange={e=>updateSet(exIdx, sIdx, 'weight', e.target.value)} className="flex-1 min-w-[60px] bg-gray-50 p-2 rounded-lg text-xs font-bold border border-gray-100 outline-none focus:border-orange-300" />
                                        <input type="number" placeholder="次數" value={s.reps} onChange={e=>updateSet(exIdx, sIdx, 'reps', e.target.value)} className="flex-1 min-w-[60px] bg-gray-50 p-2 rounded-lg text-xs font-bold border border-gray-100 outline-none focus:border-orange-300" />
                                    </div>
                                ))}
                                <button onClick={() => addSet(exIdx)} className="w-full mt-1 py-1.5 bg-orange-50 text-orange-600 text-[11px] font-bold rounded-lg border border-dashed border-orange-200"><i className="fas fa-plus"></i> 新增一組</button>
                            </div>
                        ))}
                    </div>

                    <div className="bg-white p-3 rounded-xl shadow-sm border border-gray-200 relative z-20">
                        <div className="text-[10px] font-black text-gray-400 mb-2">搜尋並加入動作</div>
                        <div className="relative">
                            <div className="flex items-center bg-gray-50 border border-gray-200 rounded-lg p-2 focus-within:border-orange-400 transition-colors">
                                <i className="fas fa-search text-gray-400 mr-2 text-xs"></i>
                                <input value={exSearch} onChange={e => { setExSearch(e.target.value); setShowExList(true); }} onFocus={() => setShowExList(true)} placeholder="搜尋動作 (如：臥推、下拉)..." className="bg-transparent outline-none text-xs font-bold w-full text-gray-700" />
                            </div>
                            {showExList && (
                                <>
                                    <div className="fixed inset-0 z-10" onClick={() => setShowExList(false)}></div>
                                    <div className="absolute top-full left-0 w-full mt-1 bg-white border border-gray-200 rounded-xl shadow-2xl z-20 max-h-56 overflow-y-auto overscroll-contain">
                                        {exSearch.trim() === '' ? (
                                            Object.entries(window.EXERCISE_DB).map(([muscle, exercises]) => (
                                                <div key={muscle}>
                                                    <div className="bg-gray-50 px-3 py-1.5 text-[10px] font-black text-gray-400 sticky top-0 border-b border-gray-100">{muscle}</div>
                                                    {exercises.map(ex => <div key={ex} onClick={() => addExercise(ex, false, muscle)} className="p-3 border-b border-gray-50 hover:bg-orange-50 cursor-pointer flex justify-between items-center text-xs font-bold text-gray-700">{ex}</div>)}
                                                </div>
                                            ))
                                        ) : (
                                            (() => {
                                                const filtered = Object.entries(window.EXERCISE_DB).flatMap(([muscle, exercises]) => 
                                                    exercises.filter(ex => ex.toLowerCase().includes(exSearch.toLowerCase())).map(ex => ({ muscle, ex }))
                                                );
                                                return filtered.length > 0 ? (
                                                    filtered.map(({muscle, ex}) => <div key={ex} onClick={() => addExercise(ex, false, muscle)} className="p-3 border-b border-gray-50 hover:bg-orange-50 cursor-pointer flex justify-between items-center text-xs font-bold text-gray-700">{ex} <span className="text-[10px] text-orange-500 bg-orange-100 px-2 py-0.5 rounded">{muscle}</span></div>)
                                                ) : (
                                                    <div className="p-4 text-xs font-bold text-gray-500 text-center flex flex-col items-center"><i className="fas fa-search text-2xl text-gray-300 mb-2"></i><div className="mb-2">找不到相關動作</div><div className="text-left bg-gray-50 p-3 rounded-xl border border-gray-200 w-full"><label className="text-[10px] font-black text-gray-600 mb-1 block">請選擇此動作的主要訓練部位：</label><select value={customMuscle} onChange={(e) => setCustomMuscle(e.target.value)} className="w-full bg-white border border-gray-200 rounded-lg p-2 text-xs font-bold text-gray-700 outline-none mb-3 shadow-sm"><option value="胸">胸</option><option value="背">背</option><option value="腿">腿</option><option value="肩">肩</option><option value="手">手</option><option value="核心">核心</option><option value="有氧與其他">有氧/其他</option></select><button onClick={() => addExercise(exSearch, true, customMuscle)} className="bg-gray-800 text-white px-4 py-2.5 rounded-lg active:scale-95 transition-transform w-full shadow-md">將「{exSearch}」加入為自訂動作</button></div></div>
                                                );
                                            })()
                                        )}
                                    </div>
                                </>
                            )}
                        </div>
                    </div>
                </div>
            )}

            {type === 'gym' && (
                <div className="grid grid-cols-2 gap-3 mb-5">
                    <div className="bg-white border border-gray-200 rounded-xl p-3 flex flex-col shadow-sm focus-within:border-orange-400"><span className="text-[10px] text-gray-400 font-bold mb-1">運動時長 (分鐘)</span><input type="number" value={duration} onChange={e=>setDuration(e.target.value)} className="bg-transparent font-black text-sm outline-none w-full" placeholder="0" /></div>
                    <div className="bg-white border border-gray-200 rounded-xl p-3 flex flex-col shadow-sm focus-within:border-orange-400"><span className="text-[10px] text-gray-400 font-bold mb-1">消耗熱量 (大卡)</span><input type="number" value={calories} onChange={e=>setCalories(e.target.value)} className="bg-transparent font-black text-sm outline-none w-full" placeholder="0" /></div>
                </div>
            )}
            
            {type === 'meal' && (
                <div className="mb-5 bg-green-50/50 p-4 rounded-2xl border border-green-100">
                    <div className="mb-4"><button onClick={() => aiFileRef.current.click()} disabled={aiRec || images.length >= 5} className="w-full py-3.5 bg-gradient-to-r from-blue-500 to-purple-500 text-white rounded-xl text-sm font-black shadow-lg disabled:opacity-50">{aiRec ? '辨識中...' : '✨ 拍照/上傳 讓 Afitus AI 智能辨識'}</button><input type="file" accept="image/*" hidden ref={aiFileRef} onChange={handleAIPredict} /></div>
                    <div className="mb-3 bg-white border border-gray-200 rounded-xl p-3 flex flex-col shadow-sm"><span className="text-[10px] text-gray-400 font-bold mb-1">總攝取熱量 (大卡)</span><input type="number" value={calories} onChange={e=>setCalories(e.target.value)} className="bg-transparent font-black text-base outline-none w-full" placeholder="0" /></div>
                    <div className="grid grid-cols-3 gap-3">
                        {[{l:'蛋白質(g)',v:protein, s:setProtein}, {l:'碳水(g)',v:carbs, s:setCarbs}, {l:'脂肪(g)',v:fat, s:setFat}].map(item => (<div key={item.l} className="bg-white border border-gray-200 rounded-xl p-3 flex flex-col shadow-sm"><span className="text-[10px] text-gray-400 font-bold mb-1">{item.l}</span><input type="number" value={item.v} onChange={e=>item.s(e.target.value)} className="bg-transparent font-black text-sm outline-none w-full" placeholder="0" /></div>))}
                    </div>
                </div>
            )}

            <textarea value={content} onChange={e=>setContent(e.target.value)} placeholder={type === 'gym' ? "額外的訓練心得紀錄..." : "分享您的健身日常..."} className="w-full h-24 p-4 bg-white border border-gray-200 rounded-2xl resize-none outline-none mb-4 font-medium text-sm shadow-sm"></textarea>
            
            <div className="flex flex-wrap gap-3 mb-6">
                {images.map((img, i) => (<div key={i} className="relative w-16 h-16 rounded-xl overflow-hidden shadow-sm"><img src={safeCreateObjectURL(img)} className="w-full h-full object-cover" /><button onClick={() => setImages(images.filter((_, idx)=>idx!==i))} className="absolute top-1 right-1 bg-black/60 text-white rounded-full w-5 h-5 flex items-center justify-center text-[10px]"><i className="fas fa-times"></i></button></div>))}
                {images.length < 5 && (<label className="w-16 h-16 border-2 border-dashed border-gray-300 rounded-xl flex flex-col items-center justify-center text-gray-400 cursor-pointer bg-gray-50 hover:bg-gray-100 transition-colors"><i className="fas fa-camera text-lg"></i><input type="file" multiple accept="image/*" hidden ref={generalFileRef} onChange={handleFile} /></label>)}
            </div>
            
            <button onClick={submit} disabled={busy || aiRec} className="w-full py-4 bg-gray-900 text-white rounded-2xl font-black text-sm shadow-lg active:scale-95 disabled:opacity-50 transition-transform">{busy ? '發佈中...' : '確認發佈'}</button>
        </div>
    );
}

const renderContentWithLinks = (text) => {
    const urlRegex = /(https?:\/\/[^\s]+)/g;
    const parts = text.split(urlRegex);
    return parts.map((part, i) => {
        if (part.match(urlRegex)) {
            return <a key={i} href={part} target="_blank" rel="noopener noreferrer" className="text-blue-500 hover:text-blue-700 underline break-all relative z-10">{part}</a>;
        }
        return part;
    });
};

function PostCard({ post, comments, user, refreshAll, onZoom, onUserClick }) {
    const [replyTo, setReplyTo] = useState(null); 
    const [showMenu, setShowMenu] = useState(false); 
    
    const [isEditing, setIsEditing] = useState(false); 
    const [editContent, setEditContent] = useState(post.content.split('===FITSHARE_WORKOUT===')[0]); 
    const [editPrivacy, setEditPrivacy] = useState(post.privacy || 'public'); 
    const [showComments, setShowComments] = useState(false);
    const [isExpanded, setIsExpanded] = useState(false);
    
    const postComms = comments.filter(c => c.postId === post.id);

    const initLiked = Array.isArray(post.likedBy) && post.likedBy.includes(user.email);
    const initLikesCount = post.likes || 0;
    const [optLikeState, setOptLikeState] = useState(initLiked);
    const [optLikeCount, setOptLikeCount] = useState(initLikesCount);
    
    const initBookmarked = Array.isArray(post.bookmarkedBy) && post.bookmarkedBy.includes(user.email);
    const [optBookmarkState, setOptBookmarkState] = useState(initBookmarked);

    useEffect(() => {
        setOptLikeState(Array.isArray(post.likedBy) && post.likedBy.includes(user.email));
        setOptLikeCount(post.likes || 0);
        setOptBookmarkState(Array.isArray(post.bookmarkedBy) && post.bookmarkedBy.includes(user.email));
    }, [post, user.email]);

    const handleOptLike = () => {
        const isNowLiked = !optLikeState;
        setOptLikeState(isNowLiked);
        setOptLikeCount(prev => isNowLiked ? prev + 1 : prev - 1);
        secureFetch('/api/posts/'+post.id+'/like', {method:'POST'})
            .catch(() => { alert("操作發生錯誤！"); setOptLikeState(!isNowLiked); setOptLikeCount(prev => !isNowLiked ? prev + 1 : prev - 1); })
            .finally(() => refreshAll());
    };

    const handleOptBookmark = () => {
        const isNowBookmarked = !optBookmarkState;
        setOptBookmarkState(isNowBookmarked); 
        secureFetch('/api/posts/' + post.id + '/bookmark', {method:'POST'})
            .catch(() => { alert("儲存收藏狀態發生錯誤！"); setOptBookmarkState(!isNowBookmarked); })
            .finally(() => refreshAll()); 
    };

    const submitComment = (text) => { secureFetch('/api/comments', { method: 'POST', headers: {'Content-Type': 'application/json'}, body: JSON.stringify({ postId: post.id, text, rootId: replyTo?.rootId, parentId: replyTo?.parentId }) }).then(() => { refreshAll(); setReplyTo(null); setShowComments(true); }); };
    const toggleCommentLike = (commentId) => secureFetch('/api/comments/'+commentId+'/like', {method:'POST'}).then(refreshAll);
    const handleDelete = () => { if(confirm('確定要刪除這篇貼文嗎？')) { secureFetch('/api/posts/'+post.id, {method:'DELETE'}).then(refreshAll); }};
    
    const handleShare = async () => {
        const shareUrl = `${window.location.origin}/?postId=${post.id}`;
        try {
            if (navigator.share && window.isSecureContext) { 
                await navigator.share({
                    title: `Afitus - ${post.userName}的動態`,
                    text: `來看看 ${post.userName} 在 Afitus 的最新分享💪！\n\n`,
                    url: shareUrl
                });
            } else if (navigator.clipboard && window.isSecureContext) { 
                await navigator.clipboard.writeText(shareUrl);
                alert('已為您將該分享專屬連結複製起來囉💪 快貼給朋友吧！');
            } else {
                const textArea = document.createElement("textarea");
                textArea.value = shareUrl;
                textArea.style.top = "0"; textArea.style.left = "0"; textArea.style.position = "fixed";
                document.body.appendChild(textArea);
                textArea.focus();
                textArea.select();
                try {
                    document.execCommand('copy');
                    alert('連結已成功強制複製💪！請直接透過「貼上」傳給朋友。');
                } catch (err) {
                    prompt('因您的系統擋截嚴重，請手動全選下方網址複製:', shareUrl);
                }
                document.body.removeChild(textArea);
            }
        } catch (err) {
            console.log('Share canceled:', err);
        }
    };

    const saveEdit = () => { 
        const jsonPart = post.content.includes('===FITSHARE_WORKOUT===') ? '===FITSHARE_WORKOUT===' + post.content.split('===FITSHARE_WORKOUT===')[1] : '';
        secureFetch('/api/posts/'+post.id, { 
            method:'PUT', 
            headers:{'Content-Type':'application/json'}, 
            body: JSON.stringify({ 
                content: editContent + jsonPart,
                privacy: editPrivacy 
            }) 
        }).then(() => { setIsEditing(false); refreshAll(); }); 
    };

    const typeBadge = { meal: { label: '飲食', bg: 'bg-green-50', text: 'text-green-600' }, gym: { label: '健身', bg: 'bg-orange-50', text: 'text-orange-600' }, post: { label: '貼文', bg: 'bg-blue-50', text: 'text-blue-600' } }[post.type] || { label: '貼文', bg: 'bg-blue-50', text: 'text-blue-600' };
    const privacyIcon = { public: 'fa-globe', friends: 'fa-user-friends', private: 'fa-lock' }[post.privacy] || 'fa-globe';
    
    const displayContent = post.content.split('===FITSHARE_WORKOUT===')[0].trim();
    const isAIPost = post.userId === 'aura@afitus.local';
    
    const MAX_LENGTH = 150;
    const shouldCollapse = displayContent.length > MAX_LENGTH;
    const truncatedContent = shouldCollapse && !isExpanded ? displayContent.substring(0, MAX_LENGTH) + '...' : displayContent;

    return (
        <div className="bg-white rounded-3xl overflow-hidden shadow-sm border border-gray-100 text-left animate-fadeIn mb-5">
            {isAIPost && (
                <div className="bg-gradient-to-r from-blue-600 to-indigo-600 text-white text-[10px] font-black px-4 py-1.5 flex items-center gap-2">
                    <i className="fas fa-robot animate-pulse"></i> Afitus AI 每日健身新知
                </div>
            )}
            
            <div className="p-4 flex items-center justify-between relative">
                <div className="flex items-center gap-3 flex-1 min-w-0">
                    <div className="w-11 h-11 rounded-full bg-gray-50 border border-gray-100 overflow-hidden flex-shrink-0 flex items-center justify-center cursor-pointer active:scale-95 transition-transform" onClick={() => onUserClick && onUserClick(post.userId)}>{post.userAvatar ? <img src={post.userAvatar.startsWith('http') || post.userAvatar.startsWith('data:') ? post.userAvatar : SERVER_URL + post.userAvatar} className="w-full h-full object-cover flex-shrink-0" /> : <i className="fas fa-user text-gray-300 text-sm"></i>}</div>
                    <div className="flex-1 min-w-0"><div className="font-black text-[13px] text-gray-900 truncate flex items-center gap-1.5">{post.userName} <i className={`fas text-gray-400 text-[9px] ${privacyIcon}`}></i></div><div className="text-[9px] text-gray-400 font-bold mt-0.5"><i className="far fa-clock"></i> {new Date(post.timestamp).toLocaleString([], {month:'2-digit', day:'2-digit', hour: '2-digit', minute:'2-digit'})}</div></div>
                </div>
                <div className="flex items-center gap-2">
                    {!isAIPost && <div className={`text-[10px] font-black px-2.5 py-1 rounded-lg ${typeBadge.bg} ${typeBadge.text}`}>{typeBadge.label}</div>}
                    {post.userId === user.email && (
                        <div className="relative z-30">
                            <button onClick={() => setShowMenu(!showMenu)} className="w-8 h-8 rounded-full bg-gray-50 flex items-center justify-center text-gray-500 hover:bg-gray-100 transition-colors"><i className="fas fa-ellipsis-v text-xs"></i></button>
                            {showMenu && (
                                <>
                                    <div className="fixed inset-0 z-40" onClick={() => setShowMenu(false)}></div>
                                    <div className="absolute right-0 mt-2 w-32 bg-white rounded-2xl shadow-lg border border-gray-100 overflow-hidden z-50 animate-slideDown">
                                        <button onClick={() => { setIsEditing(true); setShowMenu(false); }} className="w-full text-left px-4 py-3 text-xs font-bold text-gray-700 hover:bg-gray-50 border-b border-gray-50 flex items-center gap-2"><i className="fas fa-edit w-3 text-center"></i> 編輯貼文</button>
                                        <button onClick={handleDelete} 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-trash-alt w-3 text-center"></i> 刪除貼文</button>
                                    </div>
                                </>
                            )}
                        </div>
                    )}
                </div>
            </div>
            
            <div className="px-5 pb-3 text-[14px] font-medium text-gray-800 leading-relaxed whitespace-pre-wrap">
                {isEditing ? (
                    <div className="space-y-3 animate-fadeIn">
                        <textarea className="w-full bg-gray-50 border border-gray-200 rounded-xl p-3 outline-none focus:ring-1 focus:ring-blue-400 text-sm shadow-inner" rows="3" value={editContent} onChange={e => setEditContent(e.target.value)} />
                        <div className="flex justify-between items-center">
                            <select 
                                value={editPrivacy} 
                                onChange={e => setEditPrivacy(e.target.value)}
                                className="bg-gray-50 border border-gray-200 text-xs font-bold text-gray-700 rounded-lg p-1.5 outline-none focus:border-blue-400"
                            >
                                <option value="public">🌍 公開貼文</option>
                                <option value="friends">👥 僅限好友</option>
                                <option value="private">🔒 限我自己</option>
                            </select>
                            
                            <div className="flex justify-end gap-2">
                                <button onClick={() => { setIsEditing(false); setEditContent(displayContent); setEditPrivacy(post.privacy); }} className="px-4 py-1.5 rounded-full text-xs font-bold bg-gray-100 text-gray-500">取消</button>
                                <button onClick={saveEdit} className="px-4 py-1.5 rounded-full text-xs font-bold bg-blue-600 text-white shadow-md">儲存修改</button>
                            </div>
                        </div>
                    </div>
                ) : (
                    <div className="relative">
                        {renderContentWithLinks(truncatedContent)}
                        {shouldCollapse && (
                            <button 
                                onClick={() => setIsExpanded(!isExpanded)} 
                                className="text-blue-500 font-bold text-xs mt-2 hover:underline block relative z-10"
                            >
                                {isExpanded ? '收起內容' : '顯示更多...'}
                            </button>
                        )}
                    </div>
                )}
            </div>
            
            {post.type === 'gym' && (post.duration > 0 || post.calories > 0) && (
                <div className="px-5 pb-4 flex flex-wrap gap-2 text-[11px] font-black text-orange-600">
                    {post.duration > 0 && <span className="bg-orange-50 px-2.5 py-1.5 rounded-lg border border-orange-100"><i className="fas fa-stopwatch"></i> {post.duration} 分</span>}
                    {post.calories > 0 && <span className="bg-orange-50 px-2.5 py-1.5 rounded-lg border border-orange-100"><i className="fas fa-fire"></i> {post.calories} 卡</span>}
                </div>
            )}
            {post.type === 'meal' && (post.protein > 0 || post.carbs > 0 || post.fat > 0 || post.calories > 0) && (
                <div className="px-5 pb-4 flex flex-wrap gap-2 text-[11px] font-black text-green-600">
                    {post.calories > 0 && <span className="bg-red-50 text-red-500 px-2.5 py-1.5 rounded-lg border border-red-100"><i className="fas fa-fire mr-1"></i>{post.calories} 卡</span>}
                    {post.protein > 0 && <span className="bg-green-50 px-2.5 py-1.5 rounded-lg border border-green-100">蛋白 {post.protein}g</span>}
                    {post.carbs > 0 && <span className="bg-green-50 px-2.5 py-1.5 rounded-lg border border-green-100">碳水 {post.carbs}g</span>}
                    {post.fat > 0 && <span className="bg-green-50 px-2.5 py-1.5 rounded-lg border border-green-100">脂肪 {post.fat}g</span>}
                </div>
            )}

            {post.images?.length > 0 && (
                <div className="px-5 mb-4 relative group">
                    <div className="flex overflow-x-auto snap-x snap-mandatory scrollbar-hide gap-3 pb-1">
                        {post.images.map((img, i) => (
                            <div key={i} className="flex-shrink-0 w-full aspect-square snap-center relative rounded-3xl overflow-hidden cursor-zoom-in border border-gray-100 bg-gray-50 flex items-center justify-center shadow-sm" onClick={() => onZoom(post.images, i)}>
                                <img src={img.startsWith('http') || img.startsWith('data:') ? img : SERVER_URL + img} className="w-full h-full object-cover flex-shrink-0" loading="lazy" />
                                <div className="absolute bottom-4 right-4 bg-black/40 backdrop-blur-md text-white w-8 h-8 flex items-center justify-center rounded-xl"><i className="fas fa-expand text-xs"></i></div>
                            </div>
                        ))}
                    </div>
                </div>
            )}

            <div className="px-5 py-3 border-t border-gray-50 flex justify-between items-center">
                <div className="flex gap-6">
                    <button onClick={handleOptLike} className={`flex items-center gap-2 transition-all active:scale-125 ${optLikeState ? 'text-red-500' : 'text-gray-400'}`}>
                        <i className={optLikeState ? 'fas fa-heart text-xl' : 'far fa-heart text-xl'}></i> <span className="font-black text-[13px]">{optLikeCount}</span>
                    </button>
                    <div className="flex items-center gap-2 text-gray-400 cursor-pointer" onClick={() => setShowComments(!showComments)}>
                        <i className="fas fa-comment-dots text-xl"></i> <span className="font-black text-[13px]">{postComms.length}</span>
                    </div>
                </div>
                
                <div className="flex items-center gap-4">
                    <button onClick={handleOptBookmark} className={`transition-all active:scale-125 ${optBookmarkState ? 'text-yellow-500' : 'text-gray-400'}`}>
                        <i className={optBookmarkState ? 'fas fa-bookmark text-xl drop-shadow-sm' : 'far fa-bookmark text-xl'}></i>
                    </button>
                    <button onClick={handleShare} className="text-gray-400 active:scale-125 transition-transform hover:text-blue-600">
                        <i className="fas fa-share text-xl"></i>
                    </button>
                </div>
            </div>

            {showComments && (
                <div className="bg-gray-50/70 p-5 border-t border-gray-50 animate-fadeIn">
                    <div className="space-y-5 mb-4 max-h-[350px] overflow-y-auto scrollbar-hide">
                        {postComms.filter(c => !c.parentId).map((root, i) => (
                            <div className="space-y-3" key={root.id}>
                                <div className="flex gap-3 items-start">
                                    <div className="w-8 h-8 rounded-full bg-white border border-gray-200 overflow-hidden cursor-pointer flex-shrink-0 flex items-center justify-center shadow-sm" onClick={() => onUserClick && onUserClick(root.userId)}>
                                        {root.userAvatar ? <img src={root.userAvatar.startsWith('http') || root.userAvatar.startsWith('data:') ? root.userAvatar : SERVER_URL + root.userAvatar} className="w-full h-full object-cover flex-shrink-0" /> : <i className="fas fa-user text-gray-300 text-[11px]"></i>}
                                    </div>
                                    <div className="bg-white p-3 rounded-2xl rounded-tl-none text-xs flex-1 shadow-sm border border-gray-100/50">
                                        <div className="flex justify-between items-center mb-1.5">
                                            <div className="font-black text-gray-800 text-xs">{root.userName} <span className="ml-1 text-[9px] bg-blue-50 text-blue-600 px-1.5 py-0.5 rounded">B{i+1}</span></div>
                                            <div className="flex items-center gap-2.5">
                                                <button onClick={() => toggleCommentLike(root.id)} className={`flex items-center gap-1 transition-all text-[10px] font-black ${root.likedBy?.includes(user.email)?'text-red-500':'text-gray-400'}`}><i className={root.likedBy?.includes(user.email) ? 'fas fa-heart' : 'far fa-heart'}></i> {root.likes || 0}</button>
                                                <button onClick={() => setReplyTo({postId: post.id, rootId: root.id, parentId: root.id, bLabel: 'B'+(i+1)})} className="text-[10px] font-black text-gray-400 hover:text-blue-600 transition-colors">回覆</button>
                                            </div>
                                        </div>
                                        <div className="text-gray-700 text-xs font-medium leading-relaxed whitespace-pre-wrap">{root.text}</div>
                                    </div>
                                </div>
                                <div className="pl-9 border-l-2 border-gray-100 space-y-3 ml-4">
                                    {postComms.filter(c => c.rootId === root.id).map((sub, si) => (
                                        <div key={sub.id} className="flex gap-2.5 items-start">
                                            <div className="w-6 h-6 rounded-full bg-white border border-gray-200 overflow-hidden cursor-pointer flex-shrink-0 flex items-center justify-center shadow-sm" onClick={() => onUserClick && onUserClick(sub.userId)}>
                                                {sub.userAvatar ? <img src={sub.userAvatar.startsWith('http') || sub.userAvatar.startsWith('data:') ? sub.userAvatar : SERVER_URL + sub.userAvatar} className="w-full h-full object-cover flex-shrink-0" /> : <i className="fas fa-user text-gray-300 text-[9px]"></i>}
                                            </div>
                                            <div className="bg-white p-2.5 rounded-2xl rounded-tl-none text-[11px] flex-1 shadow-sm border border-gray-50">
                                                <div className="flex justify-between items-start mb-1"><div className="font-bold text-gray-800">{sub.userName} <span className="text-[8px] text-gray-400 ml-1">B{i+1}-{si+1}</span></div><button onClick={() => toggleCommentLike(sub.id)} className={`flex items-center gap-1 transition-all text-[9px] font-black ${sub.likedBy?.includes(user.email)?'text-red-500':'text-gray-400'}`}><i className={sub.likedBy?.includes(user.email) ? 'fas fa-heart' : 'far fa-heart'}></i> {sub.likes || 0}</button></div>
                                                <div className="text-gray-600 leading-relaxed whitespace-pre-wrap">{sub.text}</div>
                                            </div>
                                        </div>
                                    ))}
                                </div>
                            </div>
                        ))}
                    </div>
                    <div className="flex flex-col gap-2 relative">
                        {replyTo?.postId === post.id && (
                            <div className="text-[11px] font-black text-blue-600 bg-blue-50 px-3 py-2 rounded-xl flex justify-between items-center border border-blue-100 animate-fadeIn">
                                <span>正在回覆 <span className="underline">{replyTo.bLabel}</span></span><button onClick={() => setReplyTo(null)} className="hover:text-blue-800 w-6 h-6 rounded-full bg-blue-100 flex items-center justify-center"><i className="fas fa-times"></i></button>
                            </div>
                        )}
                        <div className="flex gap-2">
                            <input id={`input-${post.id}`} className="flex-1 bg-white border border-gray-200 rounded-full px-5 py-2.5 text-sm font-bold outline-none focus:border-blue-400 transition-all shadow-inner" placeholder={replyTo?.postId === post.id ? `回覆 ${replyTo.bLabel}...` : "留個言鼓勵一下！"} onKeyDown={e => { if(e.key === 'Enter' && e.target.value.trim()) { submitComment(e.target.value); e.target.value = ''; } }} />
                            <button onClick={() => { const el = document.getElementById(`input-${post.id}`); if(el.value.trim()) { submitComment(el.value); el.value=''; } }} className="bg-blue-600 text-white w-10 h-10 flex items-center justify-center rounded-full shadow-md active:scale-90 flex-shrink-0 transition-transform"><i className="fas fa-paper-plane text-xs -ml-0.5"></i></button>
                        </div>
                    </div>
                </div>
            )}
        </div>
    );
}
