import React, { useEffect, useMemo, useRef, useState } from "react";
import PostCard from "./PostCard";
import { matchesContentFilter } from "../Filters/ContentFilters";

export default function PostList({ posts, loading, error, selectedPost, onSelectPost, onPostDeleted, onPostUpdated, contentFilter = "all" }) {
  const [visibleCount, setVisibleCount] = useState(1);
  const listRef = useRef(null);
  const sentinelRef = useRef(null);

  const filtered = useMemo(
    () => posts.filter((p) => matchesContentFilter(p, contentFilter)),
    [posts, contentFilter]
  );

  useEffect(() => {
    setVisibleCount(1);
  }, [contentFilter]);

  useEffect(() => {
    const sentinel = sentinelRef.current;
    if (!sentinel) return;
    const observer = new IntersectionObserver(
      (entries) => {
        const hit = entries && entries[0];
        if (!hit || !hit.isIntersecting) return;
        setVisibleCount((c) => Math.min(filtered.length, c + 2));
      },
      { root: null, rootMargin: "400px 0px", threshold: 0 }
    );
    observer.observe(sentinel);
    return () => observer.disconnect();
  }, [filtered.length]);

  return (
    <div className="post-list" ref={listRef}>
        {error && <p className="status-text status-error">{error}</p>}

        {filtered.slice(0, visibleCount).map((p) => (
          <PostCard
            key={p.id ?? p._id}
            post={p}
            selected={selectedPost && (selectedPost.id ?? selectedPost._id) === (p.id ?? p._id)}
            onSelect={onSelectPost}
            onPostDeleted={onPostDeleted}
            onPostUpdated={onPostUpdated}
          />
        ))}

      {!loading && filtered.length === 0 && <p className="status-text">No posts found</p>}
      {filtered.length > visibleCount ? <div ref={sentinelRef} className="sw-wall-sentinel" /> : null}
    </div>
  );
}
