import { siteFetch } from "@/lib/siteApi";
import type { ComponentLibraryRecord } from "@/lib/mergeBlockContent";

export const COMPONENT_LIBRARY_VERSION_KEY = "orion-component-library-version";
export const COMPONENT_LIBRARY_UPDATED_EVENT = "orion-component-library-updated";

export function notifyComponentLibraryUpdated(): void {
  if (typeof window === "undefined") return;
  try {
    localStorage.setItem(COMPONENT_LIBRARY_VERSION_KEY, String(Date.now()));
  } catch {
    // ignore
  }
  window.dispatchEvent(new Event(COMPONENT_LIBRARY_UPDATED_EVENT));
}

export function readComponentLibraryVersion(): string | null {
  if (typeof window === "undefined") return null;
  try {
    return localStorage.getItem(COMPONENT_LIBRARY_VERSION_KEY);
  } catch {
    return null;
  }
}

/** Public site: component templates for runtime merge (authenticated site session). */
export async function fetchPublicComponentDefaults(): Promise<ComponentLibraryRecord[]> {
  const res = await siteFetch("/api/components/defaults");
  if (!res.ok) throw new Error("Failed to load component defaults");
  const data = (await res.json()) as { components?: ComponentLibraryRecord[] };
  return data.components ?? [];
}

/** Admin dashboard: full active component list (uses Bearer token like other admin APIs). */
export async function fetchAdminComponentDefaults(): Promise<ComponentLibraryRecord[]> {
  const { adminApi, adminEndpoints } = await import("@/admin/api");
  const data = await adminApi.get<{ components?: Array<{
    id: number;
    slug: string;
    name?: string;
    content?: Record<string, unknown> | null;
  }> }>(adminEndpoints.components);

  return (data.components ?? []).map((c) => ({
    id: c.id,
    slug: c.slug,
    name: typeof c.name === "string" ? c.name : undefined,
    content: c.content ?? {},
  }));
}
