import { useLoaderData } from "react-router";
import StaticPost from "../components/staticPost";
import type { PostContent } from "../components/post";

// Server-side loader - runs in Cloudflare Worker
export async function loader({ context }: { context: { cloudflare: { env: { API: Fetcher } } } }) {
  const env = context.cloudflare.env;
  
  // Use service binding instead of fetch()
  const response = await env.API.fetch(new Request("http://internal/feed"));
  
  if (!response.ok) {
    throw new Response("Failed to load feed", { status: response.status });
  }
  
  const feedContent: PostContent[] = await response.json();
  return { feedContent };
}

// Client component - no useEffect needed!
export default function Home() {
  const { feedContent } = useLoaderData<typeof loader>();

  if (!feedContent || feedContent.length === 0) {
    return <p>No posts found.</p>;
  }

  return (
    <>
      {feedContent.map((post) => (
        <StaticPost key={post.id} postContent={post} />
      ))}
    </>
  );
}