/**
 * 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`). Use the `../node_modules/...`
 * form shown here, not `/node_modules/...` — see "Why the glob is entry-relative,
 * not root-relative" below; the same reasoning applies to a hand-written
 * scoped glob as to the auto-discovery globs this file installs by default.
 *
 * ## Why the glob is entry-relative, not root-relative
 *
 * `import.meta.glob` only accepts a small set of static forms (`/`-rooted,
 * `./`, `../`, `**\/`, or a `#`-subpath with a literal `*`), and each resolves
 * via a literal path join, not module resolution (confirmed against Vite 8's
 * `toAbsoluteGlob`, gh#287). A `/`-rooted glob joins to Vite's CONFIGURED
 * PROJECT ROOT — for a consumer app, that only reaches `@phosphor-icons/core`
 * when it's ALSO hoisted to that exact root. Under pnpm's default
 * (non-hoisted, symlinked) linking, a package you depend on only
 * TRANSITIVELY — `@phosphor-icons/core` is a dependency of THIS package, not
 * necessarily your app's — is linked only inside that package's own
 * resolution scope, never flattened into your app's top-level `node_modules`.
 * A root-rooted glob then silently matches zero files.
 *
 * A `../`-prefixed glob instead joins to THIS FILE'S OWN directory
 * (`core/`), one level inside `@adia-ai/web-components` — so `../node_modules`
 * reaches `@adia-ai/web-components`'s own local `node_modules`, which pnpm
 * always populates with a package's own direct dependencies (a symlink into
 * the pnpm store) regardless of whether your app also hoists them. This
 * holds for the published package too — `core/icons-phosphor.js` ships at
 * the same one-level depth (see `package.json`'s `files` field). Verified
 * empirically against a real hoisting-gap install (a pnpm workspace where
 * `@phosphor-icons/core` is declared only by a nested package, not the
 * workspace root): the root-rooted form matches zero files; the
 * entry-relative form matches the full set with real content.
 *
 * ## Vite dep-optimizer pre-bundling (gh#287, second independent failure mode)
 *
 * In DEV, Vite pre-bundles bare-specifier dependencies with esbuild
 * (`optimizeDeps`) for faster cold starts, BEFORE its own plugin pipeline
 * (which includes the glob transform) ever sees them. Confirmed empirically:
 * when this package gets swept into that pre-bundling step, esbuild's scan
 * transforms each `import.meta.glob(...)` call into a literal `Object.assign({})`
 * — no exception, `hasViteGlob` stays `true`, but every weight's map is empty.
 * This is indistinguishable from a genuine zero-match glob to the code below,
 * so the same `totalIcons === 0` diagnostic fires — the fix differs, though:
 * add this package to your Vite config's `optimizeDeps.exclude` so it's
 * requested directly instead of pre-bundled (confirmed empirically to restore
 * full auto-discovery with no code change):
 *
 *   // vite.config.js
 *   export default defineConfig({
 *     optimizeDeps: { exclude: ['@adia-ai/web-components', '@adia-ai/web-modules'] },
 *   });
 *
 * If you can't control the Vite config (e.g. Astro, or another framework
 * that manages it), fall back to the scoped, explicit-import recipe above —
 * plain bare-specifier imports in your OWN first-party source are never
 * swept into `optimizeDeps` in the first place.
 *
 * ## 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. gh#287 names two independent causes, both
  // producing this same empty-map symptom:
  //   1. A packaging/bundler step re-nested this file at a different depth
  //      than it ships at (breaks the `../`-relative glob's one-level-inside
  //      assumption — see "Why the glob is entry-relative" above), a Yarn
  //      Berry PnP install (virtual/zip filesystem), or @phosphor-icons/core
  //      missing entirely.
  //   2. Vite's dev-server `optimizeDeps` pre-bundled this package (see
  //      "Vite dep-optimizer pre-bundling" above) — confirmed empirically to
  //      transform the glob into a literal empty object, no exception.
  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\` (resolved ` +
      `relative to this file's own directory — hoisting-safe under pnpm, gh#287). ` +
      `Two known causes: (1) this package got pre-bundled by Vite's dev-server ` +
      `optimizeDeps, which empties the glob — add it to optimizeDeps.exclude in ` +
      `your Vite config:\n` +
      `  optimizeDeps: { exclude: ['@adia-ai/web-components', '@adia-ai/web-modules'] }\n` +
      `(2) @phosphor-icons/core is missing, or this file was re-nested to a ` +
      `different depth by a packaging step (Yarn PnP, a custom bundler). If ` +
      `neither fix applies, install loaders manually instead:\n` +
      `  import { installIconLoaders } from '@adia-ai/web-components/core/icons';\n` +
      `  import caretRight from '@phosphor-icons/core/assets/regular/caret-right.svg?raw';\n` +
      `  installIconLoaders({\n` +
      `    regular: {\n` +
      `      '/node_modules/@phosphor-icons/core/assets/regular/caret-right.svg': caretRight,\n` +
      `    },\n` +
      `  });\n` +
      `See the JSDoc header of icons-phosphor.js for the full recipe.`
    );
  }
  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 */ });
}
