import React, { useState, useEffect, useRef } from "react";
import Post from "../Post";
import "./feed.css";

function Feed() {
  const [posts, setPosts] = useState<number[]>([]);
  const [loading, setLoading] = useState(false);
  const [hasMore, setHasMore] = useState(true);
  const feedRef = useRef<HTMLDivElement | null>(null);
  const PAGE_SIZE = 10;

  // Dummy fetch function that simulates loading posts by ID
  const fetchPosts = () => {
    if (loading) return;
    setLoading(true);

    setTimeout(() => {
      setPosts((prev) => {
        const newPosts = [];
        for (let i = 0; i < PAGE_SIZE; i++) {
          newPosts.push(prev.length + i + 1);
        }
        return [...prev, ...newPosts];
      });
      setLoading(false);

      // Stop after 50 posts, just as an example
      if (posts.length + PAGE_SIZE >= 50) {
        setHasMore(false);
      }
    }, 800);
  };

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

  useEffect(() => {
    const onScroll = () => {
      const feed = feedRef.current;
      if (!feed || loading || !hasMore) return;

      if (feed.scrollTop + feed.clientHeight >= feed.scrollHeight - 100) {
        fetchPosts();
      }
    };

    const feed = feedRef.current;
    feed?.addEventListener("scroll", onScroll);
    return () => {
      feed?.removeEventListener("scroll", onScroll);
    };
  }, [loading, hasMore]);

  return (
    <div className="feedContainer">
      <main className="feedContent" ref={feedRef}>
        {posts.map((postId) => (
          <Post key={postId} postId={postId} />
        ))}
        {loading && <div className="loading">Loading more posts...</div>}
        {!hasMore && <div>No more posts</div>}
      </main>
    </div>
  );
}

export default Feed;
