"use client";

import { useEffect, useImperativeHandle, useRef, useState, type Ref } from "react";
import { isPreviewMessage, type FromPreview, type PreviewSectionData, type ToPreview } from "@/app/(site)/_lib/previewProtocol";

export type SitePreviewHandle = {
  /** Scroll the preview to a section (reported back through onScrollTo). */
  reveal: (key: string) => void;
};

type Props = {
  pageKey: string;
  sections: PreviewSectionData[];
  selected: string | null;
  lang?: string;
  dir?: "ltr" | "rtl";
  /** Preview width (px) / page width (px). */
  scale: number;
  /** Page width the preview is rendered at. */
  width: number;
  onSelect: (key: string) => void;
  /** A section's top, in page pixels (unscaled). */
  onScrollTo: (top: number) => void;
  ref?: Ref<SitePreviewHandle>;
};

/**
 * The page rendered by the website itself (/cms-preview/<key>) in an iframe, at
 * desktop width and scaled down to fit. It shows each section with the website's
 * own components and CSS, so the preview matches the live page.
 */
export function SitePreview({ pageKey, sections, selected, lang, dir, scale, width, onSelect, onScrollTo, ref }: Props) {
  const frame = useRef<HTMLIFrameElement>(null);
  const [height, setHeight] = useState(900);

  const send = (m: ToPreview) => frame.current?.contentWindow?.postMessage(m, location.origin);

  // Only re-send when what's shown actually changes (the editor re-renders a lot).
  const payload = JSON.stringify({ type: "cms-preview:state", sections, selected, lang, dir } satisfies ToPreview);
  const latest = useRef(payload);
  useEffect(() => {
    latest.current = payload;
    send(JSON.parse(payload) as ToPreview);
  }, [payload]);

  const handlers = useRef({ onSelect, onScrollTo });
  useEffect(() => {
    handlers.current = { onSelect, onScrollTo };
  });
  useEffect(() => {
    const onMessage = (e: MessageEvent) => {
      if (e.origin !== location.origin || e.source !== frame.current?.contentWindow || !isPreviewMessage(e.data)) return;
      const m = e.data as FromPreview;
      if (m.type === "cms-preview:ready") send(JSON.parse(latest.current) as ToPreview);
      else if (m.type === "cms-preview:height") setHeight(m.height);
      else if (m.type === "cms-preview:select") handlers.current.onSelect(m.key);
      else if (m.type === "cms-preview:top") handlers.current.onScrollTo(m.top);
    };
    addEventListener("message", onMessage);
    return () => removeEventListener("message", onMessage);
  }, []);

  useImperativeHandle(ref, () => ({ reveal: (key) => send({ type: "cms-preview:reveal", key }) }), []);

  return (
    <div className="pv-stage" style={{ height: height * scale }}>
      <iframe
        ref={frame}
        src={`/cms-preview/${encodeURIComponent(pageKey)}`}
        title="Website preview"
        className="pv-frame"
        style={{ width, height, transform: `scale(${scale})` }}
      />
    </div>
  );
}
