/**
 * Messages between the admin page editor and the preview iframe (/cms-preview/<key>).
 * Both are served by this app, so every message is posted to and checked against
 * the same origin.
 */

export type PreviewSectionData = { key: string; content: unknown; dirty: boolean };

/** Editor → preview. */
export type ToPreview =
  /** What to show: the sections in display order and the one being edited. */
  | { type: "cms-preview:state"; sections: PreviewSectionData[]; selected: string | null; lang?: string; dir?: "ltr" | "rtl" }
  /** Report where a section starts (answered with "top"). */
  | { type: "cms-preview:reveal"; key: string }
  /** /cms-preview/product: a product page (GET /admin/products/:id/preview). */
  | { type: "cms-preview:product"; product: unknown }
  /** /cms-preview/article: an article page (GET /admin/articles/:id/preview). */
  | { type: "cms-preview:article"; article: unknown };

/** Preview → editor. */
export type FromPreview =
  | { type: "cms-preview:ready" }
  /** Height of the rendered page in CSS pixels. */
  | { type: "cms-preview:height"; height: number }
  /** A section was clicked. */
  | { type: "cms-preview:select"; key: string }
  /** Answer to "reveal": the section's top in page pixels. */
  | { type: "cms-preview:top"; key: string; top: number };

export const isPreviewMessage = (d: unknown): d is { type: string } =>
  !!d && typeof d === "object" && typeof (d as { type?: unknown }).type === "string" && (d as { type: string }).type.startsWith("cms-preview:");
