"use client";

import { useEffect } from "react";

export function AutoPrint() {
  useEffect(() => {
    let cancelled = false;

    function waitForImages() {
      const images = Array.from(document.images);

      return Promise.all(
        images.map((img) => {
          if (img.complete) return Promise.resolve();

          return new Promise<void>((resolve) => {
            img.onload = () => resolve();
            img.onerror = () => resolve(); // never block print
          });
        })
      );
    }

    function waitForFontsSafe() {
      try {
        // Some browsers expose document.fonts but break on .ready
        if (
          "fonts" in document &&
          document.fonts &&
          typeof document.fonts.ready?.then === "function"
        ) {
          return document.fonts.ready;
        }
      } catch {
        // Ignore font readiness completely if browser misbehaves
      }

      return Promise.resolve();
    }

    async function printWhenReady() {
      await Promise.all([waitForImages(), waitForFontsSafe()]);

      if (cancelled) return;

      // Ensure layout is flushed
      requestAnimationFrame(() => {
        // Close tab AFTER print dialog completes
        window.onafterprint = () => {
          window.close();
        };

        window.print();
      });
    }

    printWhenReady();

    return () => {
      cancelled = true;
      window.onafterprint = null;
    };
  }, []);

  return null;
}
