import type { Metadata } from "next";
import { notFound } from "next/navigation";
import { draftMode } from "next/headers";
import { getEmailTemplate, type EmailTemplateType } from "../../lib/payload";
import { LiveEmailPreviewClient } from "./components/LiveEmailPreviewClient";

export const metadata: Metadata = {
  title: "E-Mail-Vorschau",
  robots: { index: false, follow: false },
};

const VALID_TYPES: EmailTemplateType[] = [
  "order-confirmation",
  "password-reset",
  "order-shipped",
  "order-cancelled",
  "order-return-requested",
  "order-returned",
  "order-tracking-added",
  "order-tracking-corrected",
  "order-delivered",
  "payment-method-switched",
  "back-in-stock",
];

const STATUS_TYPE_FALLBACK_HEADING: Record<string, string> = {
  "order-shipped": "Deine Bestellung ist unterwegs",
  "order-cancelled": "Deine Bestellung wurde storniert",
  "order-return-requested": "Deine Rücksendung wurde angefragt",
  "order-returned": "Deine Retoure wurde bearbeitet",
  "order-tracking-added": "Hier ist deine Sendungsnummer",
  "order-tracking-corrected": "Korrigierte Sendungsnummer",
  "order-delivered": "Dein Paket ist angekommen",
  "payment-method-switched": "Erledigt!",
  "back-in-stock": "Wieder da!",
};

// Entered exclusively via EmailTemplates.ts's admin.livePreview.url (a
// Payload-admin-only iframe target, see buildPreviewUrl()/api/preview) —
// not a page a real visitor would ever land on. Always reads with
// draft:true so an unsaved edit in the admin shows up here immediately;
// the actual sent email (orderEmail.ts) always reads the published version
// instead.
//
// "back-in-stock" has its own renderer (renderBackInStockHtml) rather than
// sharing the generic order-status one below — it has no order at all, so
// no order-number line, and its CTA points at the product page ("Zum
// Produkt"), not /konto/bestellungen.
export default async function EmailPreviewPage({ params }: { params: Promise<{ type: string }> }) {
  const { type } = await params;
  if (!VALID_TYPES.includes(type as EmailTemplateType)) notFound();
  const emailType = type as EmailTemplateType;

  await draftMode();
  const fallbackHeading =
    emailType === "order-confirmation"
      ? "Vielen Dank für deine Bestellung!"
      : emailType === "password-reset"
        ? "Passwort zurücksetzen"
        : STATUS_TYPE_FALLBACK_HEADING[emailType];
  const template = (await getEmailTemplate(emailType, { draft: true })) ?? {
    type: emailType,
    subject: "",
    heading: fallbackHeading,
    bodyText: "Noch kein Inhalt gespeichert — im Payload-Admin unter E-Mail-Vorlagen anlegen.",
    footerText: null,
  };

  return <LiveEmailPreviewClient type={emailType} initialTemplate={template} />;
}
