"use client";

import Link from "next/link";
import { useLivePreview } from "@payloadcms/live-preview-react";
import { Reveal } from "./Reveal";
import { renderPageBlockSync } from "./PageBlocks";
import { mapPayloadPage, type PayloadPage, type Page } from "../lib/payload";

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

// Live-previewable subset of a Pages document: the breadcrumb and the
// layout blocks (the H1 now lives in the first block, usually a "hero" —
// see HeroBlock.ts) — same "editable subset only" scope as LivePostContent.tsx
// (see that file's own comment). `testimonialsRef` blocks are skipped here
// (see renderPageBlockSync's own comment) since they need an async fetch a
// client component can't perform inline; editing that block still shows up
// once the page is saved and reloaded outside the preview iframe.
export function LivePageContent({ initialPage }: { initialPage: Page }) {
  const { data } = useLivePreview<PayloadPage>({
    initialData: initialPage as unknown as PayloadPage,
    serverURL: PAYLOAD_URL,
    depth: 2,
  });
  const page = data?.slug ? mapPayloadPage(data) : initialPage;

  return (
    <>
      <Reveal className="flex flex-col gap-4 items-start pt-10 pb-8 px-[var(--layout-padding-x)] w-full max-w-[48rem] mx-auto">
        <p className="flex items-center gap-2 text-body-sm text-text-muted">
          <Link href="/" className="hover:text-brand transition-colors">Startseite</Link>
          <span>›</span>
          <span className="text-text-primary">{page.title}</span>
        </p>
      </Reveal>

      <Reveal delay={0.1} className="w-full max-w-[48rem] mx-auto px-[var(--layout-padding-x)] pb-14 flex flex-col gap-5">
        {page.layout.map(renderPageBlockSync)}
      </Reveal>
    </>
  );
}
