/** 草稿预览：/#/preview/{id}；可走 API，或由 Playwright 注入 window.__AJZ_PREVIEW__。 */

export type PreviewPack = {
  id: string;
  blueprint: any;
  rows: Record<string, unknown>[];
  resource: string;
};

declare global {
  interface Window {
    __AJZ_PREVIEW__?: {
      id?: string;
      ok?: boolean;
      blueprint?: any;
      rows?: Record<string, unknown>[];
      resource?: string;
    };
  }
}

let active: PreviewPack | null = null;

export function getActivePreview(): PreviewPack | null {
  return active;
}

export function clearActivePreview() {
  active = null;
}

export function activatePreview(pack: PreviewPack) {
  active = pack;
}

function packFromInjected(previewId: string): PreviewPack | null {
  const inj = typeof window !== "undefined" ? window.__AJZ_PREVIEW__ : undefined;
  if (!inj?.blueprint) return null;
  if (inj.id && inj.id !== previewId) return null;
  return {
    id: String(inj.id || previewId),
    blueprint: inj.blueprint,
    rows: Array.isArray(inj.rows) ? inj.rows : [],
    resource: String(inj.resource || "records"),
  };
}

export async function fetchPreview(previewId: string): Promise<PreviewPack> {
  const injected = packFromInjected(previewId);
  if (injected) {
    activatePreview(injected);
    return injected;
  }

  const res = await fetch(`/ai/api/v1/preview/${encodeURIComponent(previewId)}`);
  const data = await res.json();
  if (!res.ok || !data?.ok) {
    throw new Error(data?.error || `预览不存在或已过期 (${res.status})`);
  }
  const pack: PreviewPack = {
    id: String(data.id || previewId),
    blueprint: data.blueprint,
    rows: Array.isArray(data.rows) ? data.rows : [],
    resource: String(data.resource || "records"),
  };
  activatePreview(pack);
  return pack;
}

export function previewRouteId(): string | null {
  const h = (window.location.hash || "").replace(/^#/, "");
  const m = h.match(/^\/?preview\/([a-zA-Z0-9_-]{6,32})\/?$/);
  return m ? m[1] : null;
}
