import { shallowRef } from "vue";
/**
 * usePageData composable:
 * - Loads localized JSON content that was eagerly bundled at build time.
 * - If the JSON is an array and a `slug` is provided, returns the matching item.
 * - Otherwise returns the whole JSON payload.
 * - Exposes the result as a shallowRef for lightweight reactivity.
 */
// Preload JSON files eagerly (SSG-safe)

const jsonModules = import.meta.glob("../data/**/*.json", { eager: true });

// Fetch page data for a locale; optionally filter by slug
export function usePageData<T>(page: string, locale: string, slug?: string) {
  // Result holder (reactive)
  const data = shallowRef<T | null>(null);
  // Build module path for the requested page and locale
  const path = `../data/${page}/${locale}.json`;
  // Look up the eagerly-imported JSON module
  const module = jsonModules[path] as any;
  // Module found: extract its default export
  if (module?.default) {
    // JSON payload (object or array)
    const payload = module?.default ?? null;
    // If a slug is provided and payload is a list, return the matching item
    if (slug && Array.isArray(payload)) {
      // Find item with matching slug
      const found =
        (payload as any[]).find((item: any) => item && item.slug === slug) ??
        null;
      data.value = (found as T) ?? null;
    } else {
      data.value = payload as T;
    }
  }
  // Module missing: warn and set null
  else {
    console.warn(`[usePageData] Missing data for ${page}/${locale}.json`);
    data.value = null;
  }
  // Return the shallowRef so consumers can watch/react to it
  return data;
}
