'use client';

/**
 * Lazy loader for `material-file-icons`. The package is an optional dependency:
 * if it's installed in the consumer's tree, we render its rich VSCode-style
 * SVGs; if not, the loader resolves to `null` and `<FileIcon>` falls back to a
 * Lucide icon. Either way, ui-tools never throws or warns about a missing
 * package.
 *
 * Resolution is cached per-process so we don't re-import on every render.
 */

type GetIconFn = (name: string) => { svg: string } | undefined;

let cached: GetIconFn | null | undefined;
let inflight: Promise<GetIconFn | null> | null = null;

export async function loadMaterialIcons(): Promise<GetIconFn | null> {
  if (cached !== undefined) return cached;
  if (inflight) return inflight;

  inflight = (async () => {
    try {
      // Computed specifier so bundlers don't try to eagerly resolve it.
      const specifier = 'material-file-icons';
      const mod = (await import(/* @vite-ignore */ specifier)) as {
        getIcon?: GetIconFn;
        default?: { getIcon?: GetIconFn };
      };
      const fn = mod.getIcon ?? mod.default?.getIcon ?? null;
      cached = fn;
      return fn;
    } catch {
      cached = null;
      return null;
    } finally {
      inflight = null;
    }
  })();

  return inflight;
}

/** Synchronous accessor — returns null until `loadMaterialIcons` resolves. */
export function getMaterialIconsSync(): GetIconFn | null {
  return cached ?? null;
}
