/**
 * Reference Solution: Presentation Tool with Visual Editing overlays in Next.js
 *
 * Demonstrates:
 * - Configuring the Presentation tool in sanity.config.ts
 * - Setting up resolve.locations for document-to-URL mapping
 * - Enabling visual editing overlays in the Next.js frontend
 * - Draft mode integration with VisualEditing component
 * - Stega encoding for click-to-edit functionality
 */

// === Part 1: Studio Configuration (sanity.config.ts) ===

import { defineConfig } from "sanity"
import { structureTool } from "sanity/structure"
import { presentationTool } from "sanity/presentation"
import { defineLocations } from "sanity/presentation"

const presentationConfig = presentationTool({
  previewUrl: {
    previewMode: {
      enable: "/api/draft-mode/enable",
    },
  },
  resolve: {
    locations: {
      // Map each document type to its frontend URL(s)
      post: defineLocations({
        select: {
          title: "title",
          slug: "slug.current",
        },
        resolve: (doc) => ({
          locations: [
            {
              title: doc?.title || "Untitled",
              href: `/posts/${doc?.slug}`,
            },
            { title: "Home", href: "/" },
          ],
        }),
      }),

      page: defineLocations({
        select: {
          title: "title",
          slug: "slug.current",
        },
        resolve: (doc) => ({
          locations: [
            {
              title: doc?.title || "Untitled",
              href: `/${doc?.slug}`,
            },
          ],
        }),
      }),
    },
  },
})

export default defineConfig({
  name: "default",
  title: "My Studio",
  projectId: "your-project-id",
  dataset: "production",
  plugins: [structureTool(), presentationConfig],
})

// === Part 2: Next.js Draft Mode API Route (app/api/draft-mode/enable/route.ts) ===

import { draftMode } from "next/headers"
import { redirect } from "next/navigation"
import { validatePreviewUrl } from "@sanity/preview-url-secret"
import { client } from "@/sanity/client"

// GET handler that the Presentation tool calls to enable draft mode
export async function GET(request: Request) {
  const { isValid, redirectTo = "/" } = await validatePreviewUrl(
    client.withConfig({ token: process.env.SANITY_API_READ_TOKEN }),
    request.url,
  )

  if (!isValid) {
    return new Response("Invalid secret", { status: 401 })
  }

  ;(await draftMode()).enable()
  redirect(redirectTo)
}

// === Part 3: Next.js Layout with VisualEditing (app/layout.tsx) ===

import { VisualEditing } from "next-sanity"

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

  return (
    <html lang="en">
      <body>
        {children}
        {/* VisualEditing enables click-to-edit overlays in Presentation tool */}
        {isDraftMode && <VisualEditing />}
      </body>
    </html>
  )
}

// === Part 4: Sanity Client with Stega (src/sanity/client.ts) ===

import { createClient } from "next-sanity"

// The client encodes invisible stega strings into text content.
// These strings let VisualEditing know which document field each
// piece of text came from, enabling click-to-edit overlays.
export const client = createClient({
  projectId: "your-project-id",
  dataset: "production",
  apiVersion: "2024-01-01",
  useCdn: true,
  // Enable stega encoding only in draft mode
  stega: {
    studioUrl: "/studio",
  },
})
