"use client";

import dynamic from "next/dynamic";
import { useLivePreview } from "@payloadcms/live-preview-react";
import { InvoiceDocument, SAMPLE_INVOICE_ORDER } from "@einfach-produktiv/invoicing";
import type { CompanySettings } from "../../lib/payload";

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

// @react-pdf/renderer's PDFViewer renders into an <iframe> via direct DOM
// access — it has to be excluded from the server render pass entirely
// (ssr: false), unlike the HTML-string email previews elsewhere in this
// app, which can render server-side fine since they're just
// dangerouslySetInnerHTML.
const PDFViewer = dynamic(() => import("@react-pdf/renderer").then((mod) => mod.PDFViewer), { ssr: false });

// Same useLivePreview() mechanism as LiveEmailPreviewClient.tsx — connects
// to the Payload admin's iframe via postMessage and updates `data` as the
// admin edits company-settings fields, no save required. Renders through
// the exact same InvoiceDocument component the real invoice PDF uses
// (app/lib/invoicePdf.tsx), against a fixed sample order
// (SAMPLE_INVOICE_ORDER) — there's no "current" real order to preview
// against generically, same reasoning as the email-templates preview's
// own SAMPLE_ORDER.
export function LiveCompanySettingsPreviewClient({ initialSettings }: { initialSettings: CompanySettings }) {
  const { data } = useLivePreview<CompanySettings>({
    initialData: initialSettings,
    serverURL: PAYLOAD_URL,
    depth: 0,
  });

  return (
    <PDFViewer style={{ width: "100%", height: "100vh", border: "none" }}>
      {/* kleinunternehmer isn't part of InvoiceSeller (it's snapshotted
          per-order, not read live off the seller — see invoicePdf.tsx's
          own comment) — merged onto the sample order here only, so an
          admin toggling the checkbox sees the §19 notice reflected live
          without this preview needing its own separate mechanism. */}
      <InvoiceDocument order={{ ...SAMPLE_INVOICE_ORDER, kleinunternehmer: data.kleinunternehmer }} seller={data} />
    </PDFViewer>
  );
}
