"use client";

const ISLAND_MANIFEST_URL = "/api/leptos-tiptap-runtime/manifest.json";

export type LeptosTiptapIslandManifest = {
  entryAssetPath: string | null;
  wasmAssetPath: string | null;
  assetPaths: string[];
  generatedRootPath: string | null;
};

export type LeptosTiptapIslandAssetUrls = {
  manifest: LeptosTiptapIslandManifest | null;
  entryAssetUrl: string | null;
  wasmAssetUrl: string | null;
};

export function buildLeptosTiptapIslandAssetUrl(assetPath: string | null): string | null {
  if (!assetPath) {
    return null;
  }
  return `/api/leptos-tiptap-runtime/${assetPath}`;
}

export async function loadLeptosTiptapIslandAssets(): Promise<LeptosTiptapIslandAssetUrls> {
  const response = await fetch(ISLAND_MANIFEST_URL, { cache: "no-store" }).catch(() => null);
  if (!response || !response.ok) {
    return {
      manifest: null,
      entryAssetUrl: null,
      wasmAssetUrl: null,
    };
  }
  const manifest = (await response.json().catch(() => null)) as LeptosTiptapIslandManifest | null;
  return {
    manifest,
    entryAssetUrl: buildLeptosTiptapIslandAssetUrl(manifest?.entryAssetPath ?? null),
    wasmAssetUrl: buildLeptosTiptapIslandAssetUrl(manifest?.wasmAssetPath ?? null),
  };
}
