"use client";

import { useLivePreview } from "@payloadcms/live-preview-react";
import {
  renderOrderConfirmationHtml,
  renderPasswordResetHtml,
  renderOrderStatusHtml,
  ORDER_STATUS_EMAIL_ICON,
  SAMPLE_ORDER,
  type EmailTemplateContent,
} from "../../../lib/emailTemplates";
import type { EmailTemplateType } from "../../../lib/payload";

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

// Same useLivePreview() mechanism as LivePostContent.tsx (blog) — connects
// to the Payload admin's iframe via postMessage and updates `data` as the
// admin edits fields, no save required. Renders through the exact same
// renderOrderConfirmationHtml/renderPasswordResetHtml functions that build
// the real sent email (app/lib/orderEmail.ts, Customers.ts's forgotPassword
// hook on the Payload side uses its own simple template instead — see that
// hook's own comment on why the two aren't pixel-identical for
// password-reset specifically) — order-confirmation previews exactly.
export function LiveEmailPreviewClient({
  type,
  initialTemplate,
}: {
  type: EmailTemplateType;
  initialTemplate: EmailTemplateContent;
}) {
  const { data } = useLivePreview<EmailTemplateContent>({
    initialData: initialTemplate,
    serverURL: PAYLOAD_URL,
    depth: 0,
  });

  // No real company-settings fetch in this preview context — passing null
  // falls back to DEFAULT_LEGAL_FOOTER_LINES (placeholder Anbieterkennzeichnung)
  // inside buildLegalFooterLines(), same shape as the real send just with
  // placeholder business data.
  const html =
    type === "order-confirmation"
      ? renderOrderConfirmationHtml(data, SAMPLE_ORDER, null)
      : type === "password-reset"
        ? renderPasswordResetHtml(data, "https://einfach-produktiv.mk360.de/konto/passwort-zuruecksetzen?token=beispiel-token", null)
        : renderOrderStatusHtml(
            data,
            ORDER_STATUS_EMAIL_ICON[type] ?? "✓",
            SAMPLE_ORDER.orderNumber,
            `https://einfach-produktiv.mk360.de/konto/bestellungen/${SAMPLE_ORDER.orderNumber}`,
            null,
          );

  return (
    <div style={{ background: "#f4f2ee", minHeight: "100vh", padding: "32px 0" }}>
      <div dangerouslySetInnerHTML={{ __html: html }} />
    </div>
  );
}
