/**
 * Reference Solution: Sanity Integration with Remix
 *
 * Demonstrates:
 * - Creating a Sanity client configured for Remix
 * - Using GROQ queries in Remix loader functions
 * - Fetching content with client.fetch() in loaders
 * - Rendering content with useLoaderData
 * - Portable text rendering with @portabletext/react
 */

// === Part 1: Sanity Client (app/sanity/client.ts) ===

import { createClient } from "@sanity/client"

export const client = createClient({
  projectId: "your-project-id",
  dataset: "production",
  apiVersion: "2024-01-01",
  // Use CDN for published content in production
  useCdn: process.env.NODE_ENV === "production",
})

// === Part 2: Posts List Route (app/routes/posts._index.tsx) ===

import type { LoaderFunctionArgs } from "@remix-run/node"
import { useLoaderData, Link } from "@remix-run/react"

const POSTS_QUERY = `*[_type == "post"] | order(publishedAt desc) {
  _id,
  title,
  "slug": slug.current,
  publishedAt,
  excerpt,
}`

export async function loader({ request }: LoaderFunctionArgs) {
  const posts = await client.fetch(POSTS_QUERY)
  return { posts }
}

export default function PostsIndex() {
  const { posts } = useLoaderData<typeof loader>()

  return (
    <main>
      <h1>Blog Posts</h1>
      <ul>
        {posts.map((post) => (
          <li key={post._id}>
            <Link to={`/posts/${post.slug}`}>
              <h2>{post.title}</h2>
              <p>{post.excerpt}</p>
              <time dateTime={post.publishedAt}>
                {new Date(post.publishedAt).toLocaleDateString()}
              </time>
            </Link>
          </li>
        ))}
      </ul>
    </main>
  )
}

// === Part 3: Individual Post Route (app/routes/posts.$slug.tsx) ===

import { PortableText } from "@portabletext/react"

const POST_QUERY = `*[_type == "post" && slug.current == $slug][0] {
  _id,
  title,
  body,
  publishedAt,
  "author": author->name,
}`

export async function loader({ params }: LoaderFunctionArgs) {
  const post = await client.fetch(POST_QUERY, { slug: params.slug })
  if (!post) {
    throw new Response("Post not found", { status: 404 })
  }
  return { post }
}

export default function PostDetail() {
  const { post } = useLoaderData<typeof loader>()

  return (
    <article>
      <h1>{post.title}</h1>
      {post.author && <p>By {post.author}</p>}
      <time dateTime={post.publishedAt}>
        {new Date(post.publishedAt).toLocaleDateString()}
      </time>
      <div>
        <PortableText value={post.body} />
      </div>
    </article>
  )
}
