/**
 * Open a new browser window with the given HTML rendered inside it.
 *
 * Used for printable receipts, manifests, labels, and other server-rendered
 * HTML payloads. Using a Blob + object URL avoids `document.write` (which the
 * security linter flags as a dynamic-HTML sink), keeps the payload fully
 * sandboxed in a same-origin popup, and lets us add `rel="noopener"` on the
 * opener side without losing the rendering window.
 *
 * The HTML must come from a trusted source (your own API endpoint that
 * generates the printable markup server-side). Do not pass user-supplied
 * strings here without sanitizing first.
 */
export function openHtmlInPopup(html: string, features = "width=700,height=700"): Window | null {
  if (typeof window === "undefined") return null;
  const blob = new Blob([html], { type: "text/html;charset=utf-8" });
  const url = URL.createObjectURL(blob);
  const w = window.open(url, "_blank", features);
  if (!w) {
    URL.revokeObjectURL(url);
    return null;
  }
  // Revoke the object URL once the popup has loaded to free memory.
  // The popup window keeps a reference to the blob, so revoking the URL
  // does not unload the document.
  const revoke = () => URL.revokeObjectURL(url);
  w.addEventListener?.("load", revoke, { once: true });
  // Fallback in case `load` never fires (some browsers).
  setTimeout(revoke, 60_000);
  return w;
}
