import React, { useEffect, useState } from 'react';
import { useUser } from '../../context/UserContext';
import './UserDynamics.css';

const UserDynamics = () => {
  const { user } = useUser();
  const [dynamics, setDynamics] = useState([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    if (!user?.userId) return;

    const fetchDynamics = async () => {
      try {
        const res = await fetch(`/echo/dynamic/${user.userId}/getAdynamic`);
        const data = await res.json();
        setDynamics(data.dynamic || []);
      } catch (err) {
        console.error('获取动态失败:', err);
      } finally {
        setLoading(false);
      }
    };

    fetchDynamics();
  }, [user]);

  if (loading) return <div className="user-dynamics-loading">加载中...</div>;

  return (
    <div className="user-dynamics-container">
      {/* <h2 className="user-dynamics-title">我的动态</h2> */}
      {dynamics.length === 0 ? (
        <div className="user-dynamics-empty">暂无动态</div>
      ) : (
        dynamics.map((item) => (
          <div key={item.dynamic_id} className="dynamic-card">
            <div className="dynamic-header">
              <img
                className="dynamic-avatar"
                src={item.avatar_url}
                alt={item.username}
              />
              <div className="dynamic-userinfo">
                <span className="dynamic-username">{item.username}</span>
                <span className="dynamic-time">{new Date(item.time).toLocaleString()}</span>
              </div>
            </div>
            <div className="dynamic-content">
              {item.title && <h4 className="dynamic-title">{item.title}</h4>}
              <p>{item.content}</p>
              {item.images && (
                <div className="dynamic-images">
                    {(() => {
                    let imageList = [];
                    try {
                        if (item.images.startsWith('[')) {
                        imageList = JSON.parse(item.images);
                        } else {
                        imageList = [item.images];
                        }
                    } catch (e) {
                        console.error('解析 images 出错：', e);
                    }

                    return imageList.map((img, index) => (
                        <img key={index} src={img} alt={`图${index + 1}`} />
                    ));
                    })()}
                </div>
                )}

            </div>
          </div>
        ))
      )}
    </div>
  );
};

export default UserDynamics;
