"use client";

import { useEffect, useRef, useState } from "react";
import { ArticleView } from "@/app/(site)/_components/articles/ArticleView";
import type { ArticlePageData } from "@/app/(site)/_lib/articles";
import { normalizeContent } from "@/app/(site)/_lib/content";
import { isPreviewMessage, type FromPreview, type ToPreview } from "@/app/(site)/_lib/previewProtocol";

const post = (m: FromPreview) => window.parent.postMessage(m, location.origin);

/** The admin's preview of an article page (drafts), posted by the article form. */
export function ArticlePreviewFrame() {
  const [article, setArticle] = useState<ArticlePageData | null>(null);
  const rootRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    const onMessage = (e: MessageEvent) => {
      if (e.origin !== location.origin || e.source !== window.parent || !isPreviewMessage(e.data)) return;
      const m = e.data as ToPreview;
      if (m.type === "cms-preview:article") setArticle(normalizeContent(m.article as ArticlePageData));
    };
    addEventListener("message", onMessage);
    post({ type: "cms-preview:ready" });
    return () => removeEventListener("message", onMessage);
  }, []);

  useEffect(() => {
    const root = rootRef.current;
    if (!root) return;
    const report = () => post({ type: "cms-preview:height", height: Math.ceil(root.getBoundingClientRect().height) });
    const ro = new ResizeObserver(report);
    ro.observe(root);
    report();
    return () => ro.disconnect();
  }, []);

  // Links do nothing in the preview.
  useEffect(() => {
    const stop = (e: Event) => (e.target as Element | null)?.closest?.("a") && e.preventDefault();
    document.addEventListener("click", stop, true);
    return () => document.removeEventListener("click", stop, true);
  }, []);

  return (
    <>
      <style>{`html,body{overflow:hidden}[data-reveal]{opacity:1!important;transform:none!important;transition:none!important}`}</style>
      <div ref={rootRef} style={{ display: "flow-root" }} lang={article?.language && article.language !== "en" ? article.language : undefined}>
        <main id="main">{article && <ArticleView a={{ ...article, body: article.body ?? [], related: [] }} />}</main>
      </div>
    </>
  );
}
