// Nombre "print" por donde se uso primero, pero el problema que resuelve no
// es exclusivo de impresion: cualquier foto/firma/PDF cuya URL haya quedado
// guardada como absoluta apuntando a un host interno (ej.
// "http://backend:3001/uploads/...", solo resoluble DENTRO de la red de
// Docker) nunca carga en el navegador de un usuario real, sea en una
// pantalla normal o en una vista de impresion -- por eso tambien se usa
// desde ots/[id]/{page,fotos,danos,firmas}.tsx, no solo desde components/print/.
export function normalizePrintAssetUrl(value?: string | null): string {
  const raw = String(value || "").trim();

  if (!raw) {
    return "";
  }

  try {
    const base =
      typeof window !== "undefined" ? window.location.origin : "http://localhost";
    const parsed = new URL(raw, base);

    if (parsed.pathname.startsWith("/uploads/")) {
      return `${parsed.pathname}${parsed.search}${parsed.hash}`;
    }
  } catch {
    return raw;
  }

  return raw;
}

// Las cuentas internas del sistema se llaman con guiones bajos a los lados
// (ej. "__plataforma__", el usuario con el que la plataforma opera sobre un
// tenant). Ese nombre NUNCA debe salir en un papel que se le entrega al
// cliente ni en el portal donde aprueba su cotizacion: encontrado en una
// cotizacion real de produccion, que salia firmada por "Asesor de Servicio:
// __plataforma__". Cuando el asesor es una cuenta interna se prefiere dejar
// la linea de firma en blanco (para eso esta) antes que imprimir eso.
export function nombreVisibleParaCliente(nombre?: string | null): string {
  const limpio = String(nombre || "").trim();

  if (!limpio || (limpio.startsWith("__") && limpio.endsWith("__"))) {
    return "";
  }

  return limpio;
}

function waitForImage(image: HTMLImageElement, timeoutMs: number) {
  if (image.complete && image.naturalWidth > 0) {
    return Promise.resolve();
  }

  return new Promise<void>((resolve) => {
    const timeout = window.setTimeout(resolve, timeoutMs);
    const done = () => {
      window.clearTimeout(timeout);
      resolve();
    };

    image.addEventListener("load", done, { once: true });
    image.addEventListener("error", done, { once: true });
  });
}

export async function waitForPrintReady(timeoutMs = 7000) {
  if (typeof window === "undefined") {
    return;
  }

  await (document as any).fonts?.ready?.catch?.(() => undefined);

  const images = Array.from(document.querySelectorAll("img"));
  await Promise.all(images.map((image) => waitForImage(image, timeoutMs)));

  await new Promise<void>((resolve) => window.requestAnimationFrame(() => resolve()));
  await new Promise<void>((resolve) => window.requestAnimationFrame(() => resolve()));
}

export async function printWhenReady() {
  await waitForPrintReady();
  window.print();
}
