import React, { useState, useMemo } from "react";
import PostCard from "./PostCard";

function getKmFromPost(post) {
  return post.km ?? post.distance_km ?? post.distanceKm ?? post.dist_km ?? null;
}

export default function PostList({ posts, loading, error, selectedPost, onSelectPost }) {
  const [kmFilter, setKmFilter] = useState(1000);

  const filtered = useMemo(
    () =>
      posts.filter((p) => {
        const km = getKmFromPost(p);
        if (km == null) return true;
        return km <= kmFilter;
      }),
    [posts, kmFilter]
  );

  return (
    <div className="post-list">
      <div className="post-list-header">
        <div className="km-filter">
          <label>
            Rayon : <span>{kmFilter} km</span>
          </label>
          <input
            type="range"
            min={0}
            max={1000}
            value={kmFilter}
            onChange={(e) => setKmFilter(Number(e.target.value))}
          />
        </div>
      </div>

            {error && <p className="status-text status-error">{error}</p>}

      {filtered.map((p) => (
        <PostCard
          key={p.id ?? p._id}
          post={p}
          selected={selectedPost && (selectedPost.id ?? selectedPost._id) === (p.id ?? p._id)}
          onSelect={onSelectPost}
        />
      ))}

      {!loading && filtered.length === 0 && <p className="status-text">Aucun post dans ce rayon.</p>}
    </div>
  );
}
