/**
 * Phosphor icon glob — side-effect module that wires the full
 * @phosphor-icons/core asset tree (~9000 SVGs × 6 weights) into the
 * registry exposed by `./icons.js`.
 *
 * ## When to import this
 *
 *   import '@adia-ai/web-components/core/icons-phosphor';
 *
 * Use this only when you want any Phosphor name to resolve without
 * pre-registering it. The main barrel (`import '@adia-ai/web-components'`)
 * and the core barrel (`import '@adia-ai/web-components/core'`) already
 * side-effect-import this file for zero-config users.
 *
 * ## What this costs
 *
 * `import.meta.glob` with the default lazy mode tells Vite to emit one
 * code-split chunk per matched file. The full Phosphor set is ~9000 SVGs
 * (~1500 names × 6 weights), so `vite build` emits ~9000 chunks even if
 * your app only renders 2 icons. The chunks are HTTP-cacheable, but:
 *
 *   - `vite build` graph cost scales with the Phosphor set, not your usage
 *   - `.vite/deps` cache grows >100 MB during dev
 *   - Static deploys without incremental upload push tens of thousands of
 *     tiny files on every deploy
 *   - Rollup warns "(!) Some chunks are larger than 500 KB"
 *
 * For production bundles with size SLOs, skip this side-effect import and
 * register only the icons you use:
 *
 *   import { installIconLoaders } from '@adia-ai/web-components/core/icons';
 *   installIconLoaders({
 *     regular: import.meta.glob(
 *       '/node_modules/@phosphor-icons/core/assets/regular/{caret-right,moon,sun,x}.svg',
 *       { query: '?raw', import: 'default', eager: true }
 *     ),
 *   });
 *
 * Brace-list globs are statically analyzed; only the named files are
 * emitted as chunks (or inlined when `eager: true`).
 *
 * ## Vite glob detection
 *
 * `import.meta.glob` is a build-time macro — Vite's AST transform replaces
 * each call with a literal `{ path: loader }` object before the module
 * reaches the browser. At runtime `import.meta.glob` is undefined, so a
 * direct call throws. We wrap the assignment in try/catch to handle both:
 *
 *   - Vite dev/build → rewritten to literals → try block succeeds
 *   - Static  serving → actual runtime call throws → catch falls through
 *     to the manifest fetch below
 */

import { installIconLoaders } from './icons.js';

let weightModules;
let hasViteGlob = false;
try {
  weightModules = {
    regular: import.meta.glob('/node_modules/@phosphor-icons/core/assets/regular/*.svg', { query: '?raw', import: 'default' }),
    thin:    import.meta.glob('/node_modules/@phosphor-icons/core/assets/thin/*.svg',    { query: '?raw', import: 'default' }),
    light:   import.meta.glob('/node_modules/@phosphor-icons/core/assets/light/*.svg',   { query: '?raw', import: 'default' }),
    bold:    import.meta.glob('/node_modules/@phosphor-icons/core/assets/bold/*.svg',    { query: '?raw', import: 'default' }),
    fill:    import.meta.glob('/node_modules/@phosphor-icons/core/assets/fill/*.svg',    { query: '?raw', import: 'default' }),
    duotone: import.meta.glob('/node_modules/@phosphor-icons/core/assets/duotone/*.svg', { query: '?raw', import: 'default' }),
  };
  hasViteGlob = true;
} catch (err) {
  // FB-08: distinguish "no Vite at all" (expected, ReferenceError) from
  // every other error (unexpected, worth logging). ReferenceError is the
  // signal that `import.meta.glob` doesn't exist — i.e. non-Vite static
  // serving, which is what the manifest-fetch fallback below was designed
  // for. Anything else got swallowed silently by the previous bare catch.
  if (err && !(err instanceof ReferenceError)) {
    console.warn(
      `[icons-phosphor] import.meta.glob threw an unexpected error ` +
      `(not a vanilla ReferenceError): ${err.message}. ` +
      `Falling back to manifest fetch. If you're using Vite, this likely ` +
      `means a misconfigured plugin order or glob root.`
    );
  }
}

if (hasViteGlob) {
  // FB-08: detect the silent-empty-glob case — `import.meta.glob` returns
  // `{}` when zero files match (it does NOT throw). The previous behavior
  // installed empty per-weight maps and the consumer saw an empty icon
  // registry with no diagnostic. This happens when the consumer's Vite
  // root sits below `node_modules`, or with pnpm/yarn-berry virtual paths,
  // or when this file runs from inside a published package directory
  // (its absolute-style glob is resolved relative to the Vite root, not
  // this file's directory).
  const totalIcons = Object.values(weightModules).reduce(
    (sum, weight) => sum + Object.keys(weight).length, 0
  );
  if (totalIcons === 0) {
    console.warn(
      `[icons-phosphor] No Phosphor icons matched the auto-install glob ` +
      `\`/node_modules/@phosphor-icons/core/assets/<weight>/*.svg\`. ` +
      `This usually means your Vite root sits below node_modules, you use ` +
      `pnpm/yarn-berry virtual paths, or this module is loaded from a ` +
      `published package directory. Install loaders manually from your app entry:\n` +
      `  import { installIconLoaders } from '@adia-ai/web-components/core/icons';\n` +
      `  installIconLoaders({\n` +
      `    regular: import.meta.glob(\n` +
      `      '../node_modules/@phosphor-icons/core/assets/regular/*.svg',\n` +
      `      { query: '?raw', import: 'default', eager: true }\n` +
      `    ),\n` +
      `  });`
    );
  }
  installIconLoaders(weightModules);
} else {
  // Non-Vite static serving: fetch the build-time manifest in the
  // background. No top-level await — module finishes loading immediately;
  // icons appear once the one-shot manifest fetch resolves.
  // The specifier is hidden behind a variable so Vite's static analysis
  // never tries to pre-resolve it in dev (where the file doesn't exist).
  const manifestSpec = './icons-manifest.js';
  import(/* @vite-ignore */ manifestSpec).then(({ default: manifest }) => {
    // `cdn` is an optional key added by bundle-js.mjs for CDN-distributed
    // bundles. When present, SVGs are fetched from the CDN origin rather than
    // /node_modules/ (which only exists on localhost / in a bundler context).
    const { cdn: cdnBase, ...weights } = manifest;
    const modules = Object.fromEntries(Object.entries(weights).map(([weight, names]) => {
      const base = cdnBase
        ? `${cdnBase}${weight}/`
        : `/node_modules/@phosphor-icons/core/assets/${weight}/`;
      const entries = names.map(name => {
        const path = base + name;
        const loader = () => fetch(path).then(r => r.ok ? r.text() : Promise.reject(new Error(`icon fetch failed: ${path}`)));
        return [path, loader];
      });
      return [weight, Object.fromEntries(entries)];
    }));
    installIconLoaders(modules);
  }).catch(() => { /* manifest missing — registry stays empty; consumers can registerIcon() themselves */ });
}
