/**
 * Reference Solution: Live Content with Sanity Client
 *
 * Demonstrates:
 * - Using defineLive from next-sanity to create live-updating data fetchers
 * - Server-side token-authenticated client for live content
 * - Using sanityFetch in server components for real-time data
 * - Placing SanityLive component in the layout
 * - How live content works both inside and outside Presentation tool
 */

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

import { createClient } from "next-sanity"

export const client = createClient({
  projectId: "your-project-id",
  dataset: "production",
  apiVersion: "vX", // Use "vX" for live content — latest API features
  useCdn: false, // Live content requires no CDN caching
})

// === Part 2: Live Content Setup (src/sanity/live.ts) ===

import { defineLive } from "next-sanity"

const token = process.env.SANITY_API_READ_TOKEN
if (!token) {
  throw new Error("Missing SANITY_API_READ_TOKEN environment variable")
}

// defineLive creates two exports:
// - sanityFetch: a server-side function that fetches live-updating data
// - SanityLive: a client component that subscribes to real-time updates
export const { sanityFetch, SanityLive } = defineLive({
  client: client.withConfig({ apiVersion: "vX" }),
  serverToken: token,
  browserToken: token,
})

// === Part 3: Layout with SanityLive (app/layout.tsx) ===

import { SanityLive } from "@/sanity/live"
import { VisualEditing } from "next-sanity"
import { draftMode } from "next/headers"

export default async function RootLayout({
  children,
}: {
  children: React.ReactNode
}) {
  const { isEnabled: isDraftMode } = await draftMode()

  return (
    <html lang="en">
      <body>
        {children}
        {/* SanityLive enables real-time content updates */}
        <SanityLive />
        {isDraftMode && <VisualEditing />}
      </body>
    </html>
  )
}

// === Part 4: Server Component with Live Fetch (app/page.tsx) ===

import { sanityFetch } from "@/sanity/live"

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

export default async function PostsPage() {
  // sanityFetch returns { data } — the data automatically updates in
  // real-time when content changes in the Studio, no polling needed.
  const { data: posts } = await sanityFetch({ query: POSTS_QUERY })

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

// === Part 5: Individual Post with Live Fetch (app/posts/[slug]/page.tsx) ===

import { sanityFetch } from "@/sanity/live"
import { PortableText } from "@portabletext/react"

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

export default async function PostPage({
  params,
}: {
  params: Promise<{ slug: string }>
}) {
  const { slug } = await params
  const { data: post } = await sanityFetch({
    query: POST_QUERY,
    params: { slug },
  })

  if (!post) return <div>Post not found</div>

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