// ─── Static Template Preview Cache ───
// Loads pre-rendered PDFs from /examples/{id}/main.pdf (generated by scripts/generate-previews.ts).
// No runtime LaTeX compilation needed.

import { getMupdfClient } from "@/lib/mupdf/mupdf-client";
import { createLogger } from "@/lib/debug/logger";

const log = createLogger("template-preview");

type Listener = () => void;
const listeners = new Set<Listener>();
const thumbnailCache = new Map<string, string>();
const failedIds = new Set<string>();
const pendingRequests = new Map<string, Promise<string | null>>();

function notify() {
  for (const fn of listeners) fn();
}

export function subscribeThumbnails(fn: Listener): () => void {
  listeners.add(fn);
  return () => listeners.delete(fn);
}

export function getThumbnail(templateId: string): string | undefined {
  return thumbnailCache.get(templateId);
}

export function isThumbnailFailed(templateId: string): boolean {
  return failedIds.has(templateId);
}

/** URL to the pre-rendered static PDF for a template */
export function getTemplatePdfUrl(templateId: string): string {
  return `/examples/${templateId}/main.pdf`;
}

/**
 * Load the static PDF and render page 1 as a thumbnail data URL.
 */
export async function generateThumbnail(
  templateId: string,
): Promise<string | null> {
  const cached = thumbnailCache.get(templateId);
  if (cached) return cached;

  if (failedIds.has(templateId)) return null;

  const pending = pendingRequests.get(templateId);
  if (pending) return pending;

  const promise = (async (): Promise<string | null> => {
    try {
      const url = getTemplatePdfUrl(templateId);
      const response = await fetch(url);
      if (!response.ok) throw new Error(`HTTP ${response.status}`);
      const buffer = await response.arrayBuffer();

      const client = getMupdfClient();
      const docId = await client.openDocument(buffer);

      const targetWidth = 300;
      const pngBuffer = await client.renderThumbnail(docId, 0, targetWidth);
      await client.closeDocument(docId);

      const blob = new Blob([pngBuffer], { type: "image/png" });
      const dataUrl = URL.createObjectURL(blob);

      thumbnailCache.set(templateId, dataUrl);
      notify();
      return dataUrl;
    } catch (err) {
      log.warn(`Failed to load preview for ${templateId}`, {
        error: String(err),
      });
      failedIds.add(templateId);
      notify();
      return null;
    } finally {
      pendingRequests.delete(templateId);
    }
  })();

  pendingRequests.set(templateId, promise);
  return promise;
}
