import React, { useEffect, useState, useRef } from "react";
import { db } from "../firebase/firebase";
import {
  collection,
  query,
  orderBy,
  onSnapshot,
  doc,
  getDoc,
} from "firebase/firestore";
import { formatDistanceToNow } from "date-fns";
import {
  FaHeart,
  FaComment,
  FaPaperPlane,
  FaBookmark,
} from "react-icons/fa";

// Utility to fetch user data from Firestore
const getUserData = async (userId) => {
  try {
    const userRef = doc(db, "users", userId); // Assumes users collection is keyed by UID
    const userSnap = await getDoc(userRef);

    if (userSnap.exists()) {
      const data = userSnap.data();
      console.log("Fetched user data:", data);

      const {
        username = data.name || "Unknown",
        profileImage = "",
      } = data;

      return {
        username,
        photoURL:
          profileImage.startsWith("data:") || profileImage.startsWith("http")
            ? profileImage
            : `data:image/jpeg;base64,${profileImage}`,
      };
    } else {
      console.warn("User not found for ID:", userId);
    }
  } catch (err) {
    console.error("Error fetching user data:", err);
  }

  return {
    username: "Unknown",
    photoURL: "/default-avatar.png",
  };
};

export default function PostList() {
  const [posts, setPosts] = useState([]);
  const [loading, setLoading] = useState(true);
  const userCache = useRef({}); // Persistent cache

  useEffect(() => {
    const q = query(collection(db, "posts"), orderBy("createdAt", "desc"));

    const unsubscribe = onSnapshot(q, async (snapshot) => {
      const postDocs = snapshot.docs.map((doc) => ({
        id: doc.id,
        ...doc.data(),
      }));

      const enrichedPosts = await Promise.all(
        postDocs.map(async (post) => {
          const userId = post.userId;
          console.log("Processing post from user:", userId);

          if (!userId) {
            return {
              ...post,
              user: {
                username: "Unknown",
                photoURL: "/default-avatar.png",
              },
            };
          }

          if (!userCache.current[userId]) {
            userCache.current[userId] = await getUserData(userId);
          }

          return {
            ...post,
            user: userCache.current[userId],
          };
        })
      );

      setPosts(enrichedPosts);
      setLoading(false);
    });

    return () => unsubscribe();
  }, []);

  if (loading) {
    return <p className="text-center py-6 text-gray-500">Loading posts...</p>;
  }

  if (!posts.length) {
    return <p className="text-center py-6 text-gray-500">No posts yet.</p>;
  }

  return (
    <div className="max-w-md mx-auto mt-8 space-y-8">
      {posts.map((post) => {
        const avatar = post.user?.photoURL || "/default-avatar.png";
        const username = post.user?.username || "Unknown";

        return (
          <div
            key={post.id}
            className="bg-white rounded-lg border border-gray-200 shadow-sm"
          >
            {/* Post Header */}
            <div className="flex items-center justify-between p-4">
              <div className="flex items-center gap-3">
                <img
                  src={avatar}
                  alt={username}
                  className="w-10 h-10 rounded-full object-cover border border-gray-300"
                />
                <div>
                  <p className="text-sm font-medium text-gray-900">
                    {username}
                  </p>
                  <p className="text-xs text-gray-500">
                    {formatDistanceToNow(
                      post.createdAt?.toDate?.() || new Date(),
                      { addSuffix: true }
                    )}
                  </p>
                </div>
              </div>
              <span className="text-gray-400 text-xl">⋯</span>
            </div>

            {/* Post Image */}
            {post.image && (
              <img
                src={post.image}
                alt="Post content"
                className="w-full object-cover max-h-[400px]"
              />
            )}

            {/* Action Icons */}
            <div className="flex items-center justify-between px-4 py-2">
              <div className="flex items-center gap-4 text-xl text-gray-700">
                <FaHeart className="hover:text-red-500 cursor-pointer" />
                <FaComment className="hover:text-blue-500 cursor-pointer" />
                <FaPaperPlane className="hover:text-green-500 cursor-pointer" />
              </div>
              <FaBookmark className="text-xl text-gray-700 hover:text-yellow-500 cursor-pointer" />
            </div>

            {/* Caption */}
            <div className="px-4 pb-4">
              <p className="text-sm mb-2 text-gray-800">
                <strong>{username}</strong> {post.text}
              </p>

              {/* Tags */}
              {post.tags?.length > 0 && (
                <div className="flex flex-wrap gap-2 mt-2">
                  {post.tags.map((tag, idx) => (
                    <span
                      key={idx}
                      className="text-xs bg-blue-100 text-blue-700 px-2 py-1 rounded-full"
                    >
                      #{tag}
                    </span>
                  ))}
                </div>
              )}
            </div>
          </div>
        );
      })}
    </div>
  );
}
 take the refererence form the code how the name was taken from the firestore and update this component import React, { useEffect, useState } from 'react';
import SuggestionsBar from './Sugestionbar';
import { getAuth } from "firebase/auth";
import { db } from "../firebase/firebase";
import { doc, getDoc } from "firebase/firestore";

const Profile = () => {
  const [user, setUser] = useState(null);
  const [loading, setLoading] = useState(true);

  // Fetch user data from Firestore
  useEffect(() => {
    const fetchUser = async () => {
      const auth = getAuth();
      const currentUser = auth.currentUser;
      if (!currentUser) {
        setLoading(false);
        return;
      }
      const userRef = doc(db, "users", currentUser.uid);
      const userSnap = await getDoc(userRef);
      if (userSnap.exists()) {
        setUser({
          avatar: userSnap.data().profileImage || "/default-avatar.png",
          username: userSnap.data().username || "unknown",
          name: userSnap.data().name || "",
          verified: userSnap.data().verified || false,
          stats: {
            posts: userSnap.data().posts || 0,
            followers: userSnap.data().followers || 0,
            following: userSnap.data().following ? userSnap.data().following.length : 0,
          },
          bio: userSnap.data().bio
            ? Array.isArray(userSnap.data().bio)
              ? userSnap.data().bio
              : userSnap.data().bio.split('\n')
            : [],
        });
      }
      setLoading(false);
    };
    fetchUser();
  }, []);

  if (loading) {
    return <div className="min-h-screen flex items-center justify-center bg-white text-gray-700">Loading...</div>;
  }

  if (!user) {
    return <div className="min-h-screen flex items-center justify-center bg-white text-gray-700">User not found.</div>;
  }

  return (
    <div className="min-h-screen bg-white flex flex-col items-center text-black p-0">
      {/* Profile Header */}
      <div className="w-full max-w-2xl flex flex-col sm:flex-row items-center sm:items-start gap-6 sm:gap-10 py-8 px-4">
        {/* Avatar */}
        <div className="flex-shrink-0">
          <img
            src={
              user.avatar.startsWith("http") || user.avatar.startsWith("data:")
                ? user.avatar
                : `data:image/jpeg;base64,${user.avatar}`
            }
            alt={user.username}
            className="w-28 h-28 rounded-full object-cover border-4 border-gray-200"
          />
        </div>
        {/* Info */}
        <div className="flex-1 w-full">
          {/* Username and Buttons */}
          <div className="flex flex-col sm:flex-row sm:items-center gap-3 sm:gap-4 mb-4">
            <span className="text-2xl font-light">{user.username}</span>
            {user.verified && (
              <svg className="w-5 h-5 text-blue-500 inline" fill="currentColor" viewBox="0 0 20 20">
                <path d="M10 2a2 2 0 0 1 1.8 1.1l.7 1.4 1.5.2a2 2 0 0 1 1.1 3.4l-1.1 1.1.3 1.5a2 2 0 0 1-2.9 2.1L10 12.6l-1.3.7a2 2 0 0 1-2.9-2.1l.3-1.5-1.1-1.1A2 2 0 0 1 5.8 4.7l1.5-.2.7-1.4A2 2 0 0 1 10 2z"/>
              </svg>
            )}
            <button
              className="bg-gray-100 text-black text-sm font-semibold px-4 py-1 rounded border border-gray-300 cursor-not-allowed opacity-60"
              disabled
            >
              Edit Profile
            </button>
            <button className="bg-gray-100 text-black text-sm font-semibold px-4 py-1 rounded border border-gray-300">Message</button>
            <button className="bg-gray-100 text-black text-sm font-semibold px-4 py-1 rounded border border-gray-300">Text</button>
            <button className="bg-gray-200 text-gray-700 text-xl px-2 rounded">⋯</button>
          </div>
          {/* Stats */}
          <div className="flex gap-6 mb-3 text-sm">
            <span><span className="font-semibold">{user.stats.posts}</span> Posts</span>
            <span><span className="font-semibold">{user.stats.followers}</span> Followers</span>
            <span><span className="font-semibold">{user.stats.following}</span> Following</span>
          </div>
          {/* Name */}
          <div className="font-semibold">{user.name}</div>
          {/* Bio */}
          <div className="text-sm text-gray-700">
            {user.bio.map((line, idx) => (
              <div key={idx}>{line}</div>
            ))}
          </div>
        </div>
      </div>
      {/* Suggestions Bar */}
      <div className="w-full max-w-2xl">
        <SuggestionsBar />
      </div>
    </div>
  );
};

export default Profile;