"use client";

import Image from "next/image";
import { useLivePreview } from "@payloadcms/live-preview-react";
import { Reveal } from "../../../components/Reveal";
import { RichText } from "../../../components/RichText";
import { formatDate } from "../../../lib/format";
import { mapPayloadPost, type PayloadPostDetail, type PostDetail } from "../../../lib/payload";

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

// Live-previewable subset of the blog detail page: title/categories/readTime/
// excerpt/byline, the thumbnail, and the RichText body — the fields an
// editor actually watches update while typing. The author bio card,
// "Weiterlesen" card, and Footer stay static in page.tsx: they either
// aren't post-specific content (bio) or are about a *different* post
// (nextPost), not the document currently open in the admin.
export function LivePostContent({ initialPost }: { initialPost: PostDetail }) {
  const { data } = useLivePreview<PayloadPostDetail>({
    initialData: initialPost as unknown as PayloadPostDetail,
    serverURL: PAYLOAD_URL,
    depth: 2,
  });
  const post = data?.slug ? mapPayloadPost(data) : initialPost;

  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">
        <div className="flex items-center gap-2 font-semibold text-text-muted text-body-sm uppercase tracking-wide">
          <span>{post.categories.join(", ")}</span>
          <span>•</span>
          <span>{post.readTime} Min</span>
        </div>
        <p
          className="font-semibold text-[clamp(2.25rem,1.393rem+1.786vw,3rem)] text-text-primary leading-[1.15]"
          style={{ fontFamily: "var(--font-playfair)" }}
        >
          {post.title}
        </p>
        <p className="text-body text-text-muted">{post.excerpt}</p>
        <div className="flex items-center gap-3 pt-1">
          <div className="relative size-9 shrink-0 rounded-full overflow-hidden">
            <Image alt="Björn" src="/about-author.jpg" fill sizes="36px" className="object-cover" />
          </div>
          <p className="text-body-sm text-text-primary">
            Björn <span className="text-text-muted">• {formatDate(post.publishedAt)}</span>
          </p>
        </div>
      </Reveal>

      {post.thumbnail && (
        <Reveal delay={0.1} className="w-full max-w-[70rem] mx-auto px-[var(--layout-padding-x)] pb-10">
          <div className="relative w-full aspect-[1120/460] rounded-md overflow-hidden bg-bg-muted">
            <Image alt="" src={post.thumbnail} fill sizes="(min-width: 1120px) 70rem, 100vw" className="object-cover" />
          </div>
        </Reveal>
      )}

      <Reveal delay={0.15} className="flex flex-col gap-6 w-full max-w-[48rem] mx-auto px-[var(--layout-padding-x)] pb-10">
        <RichText content={post.content} quoteLabel={post.quoteLabel} />
      </Reveal>
    </>
  );
}
