"use client";

import { useLivePreview } from "@payloadcms/live-preview-react";
import { TestimonialsGrid } from "./TestimonialsGrid";
import { mapPayloadTestimonial, type PayloadTestimonial, type Testimonial } from "../lib/payload";

const PAYLOAD_URL = process.env.NEXT_PUBLIC_PAYLOAD_URL || "https://payload.mk360.de";

// Live Preview is document-scoped (Payload's admin has exactly one
// testimonial open at a time), but this page renders a *grid* of several —
// so unlike LiveRichText/LivePostContent (which map 1:1 to a single
// document), this only swaps in the one testimonial currently being edited
// (matched by id) and leaves the rest of the grid as initially fetched.
// initialData starts empty since we don't know which of the `testimonials`
// is open until the first postMessage arrives — acceptable because this
// component only ever mounts inside the Payload admin's own preview
// iframe (see the `isPreview` gate in todo-cards/newsletter/challenge's
// page.tsx), never for ordinary site visitors.
export function LiveTestimonialsGrid({ testimonials }: { testimonials: Testimonial[] }) {
  const { data } = useLivePreview<Partial<PayloadTestimonial>>({
    initialData: {},
    serverURL: PAYLOAD_URL,
    depth: 1,
  });

  const merged =
    data.id !== undefined
      ? testimonials.map((t) => (t.id === data.id ? mapPayloadTestimonial(data as PayloadTestimonial) : t))
      : testimonials;

  return <TestimonialsGrid testimonials={merged} />;
}
