import { checkPreviewCompatibility, type VisualPreviewRuntimeReceipt } from "@roottale/cms-core/visual-edit";
import { siteVisualEditorOrigins } from "../lib/visual-preview-origins";
import {
  RootTaleVisualEditBridge,
  visualEditAttributes,
  type VisualRenderReceipt,
} from "@roottale/cms-renderer-next/visual-edit";

interface Props {
  entityId: string;
  title: string;
  rows: readonly { _id: string; label: string; description: string }[];
  sectionState?: "visible" | "hidden" | "deleted";
  /** 인증된 서버가 조회한 snapshot과 실제 공개 의존 버전으로만 만든다. */
  receipt?: VisualRenderReceipt;
  /** 서버가 사이트 env에서 읽은 관리자 origin. 미리보기 CSP에도 같은 목록을 설정한다. */
  allowedOrigins?: readonly string[];
}

/** 공개·미리보기가 함께 사용하는 템플릿. 고객 사이트의 기존 JSX에 속성만 연결한다. */
export function VisualContentPreview({ entityId, title, rows, sectionState, receipt, allowedOrigins = siteVisualEditorOrigins() }: Props) {
  const isPreview = receipt !== undefined;
  return <main>
    <h1 {...visualEditAttributes({ entityId, fieldKey: "title", path: ["hero", "title"] }, isPreview)}>{title}</h1>
    {sectionState !== "hidden" && sectionState !== "deleted" ? <table>
      <caption>비교 항목</caption>
      <tbody>{rows.map(row => <tr key={row._id}>
        <th scope="row" {...visualEditAttributes({
          entityId, fieldKey: "label", path: ["comparison", "rows", `@${row._id}`, "label"],
        }, isPreview)}>{row.label}</th>
        <td {...visualEditAttributes({
          entityId, fieldKey: "description", path: ["comparison", "rows", `@${row._id}`, "description"],
        }, isPreview)}>{row.description}</td>
      </tr>)}</tbody>
    </table> : null}
    {receipt ? <RootTaleVisualEditBridge receipt={receipt}
      allowedOrigins={allowedOrigins} /> : null}
  </main>;
}

/** 인증·URL의 ID 대조를 마친 서버에서 실제로 읽은 본문·의존 버전만 전달한다. */
export function CompatibleVisualContentPreview({ runtimeReceipt, templateVersion, ...props }: Props & {
  receipt: VisualRenderReceipt;
  runtimeReceipt: VisualPreviewRuntimeReceipt;
  templateVersion: string;
}) {
  if (!checkPreviewCompatibility(props.receipt, runtimeReceipt, templateVersion)) {
    return <p>미리보기 갱신이 필요합니다. 사이트 계약을 다시 설치해 주세요.</p>;
  }
  return <VisualContentPreview {...props} />;
}
