import React, { useEffect, useState } from "react";

/**
 * Full-page viewer for a template handed over via localStorage.
 *
 * Rendered in a sandboxed iframe rather than injected into this document, for
 * two reasons:
 *
 *   Safety — the html is author-supplied and this route is inside the
 *   authenticated console. Injecting it with dangerouslySetInnerHTML would let
 *   a template run script in the console's origin, with the reader's session.
 *   sandbox="" allows no scripts, no forms, no same-origin access.
 *
 *   Accuracy — an email's <style> block is written assuming it owns the
 *   document. Injected inline it both leaks into the console's styles and
 *   inherits them, so what you see is not what an inbox renders.
 */
export default function EDMPreviewPage() {
  const [html, setHtml] = useState<string | null>(null);

  useEffect(() => {
    setHtml(
      localStorage.getItem("edm_preview_html") ??
        "<div style='padding:20px;font-family:sans-serif'>No preview content found. Go back and click “View in browser” again.</div>",
    );
  }, []);

  if (html === null) return null;

  return (
    <iframe
      title="EDM preview"
      srcDoc={html}
      sandbox=""
      style={{
        position: "fixed",
        inset: 0,
        width: "100%",
        height: "100%",
        border: "none",
        backgroundColor: "#fff",
      }}
    />
  );
}
