/**
 * @wrnexus/ui — the Wire UI component library.
 *
 * Components are `.wrn` files under `components/`, auto-discovered by the
 * framework (the router scans this directory in addition to the app's own
 * `app/components`). Mount them in any page with `data-component="<name>"`.
 * Their styles live in a single themeable stylesheet, `ui.css`, served once at
 * `/__wrnexus/ui.css` — every class uses `var(--wire-*)` theme tokens.
 *
 * Override, in increasing order of power:
 *   1. theme tokens (change `--wire-color-primary`, etc.)
 *   2. redefine a `.wire-*` class in your own CSS (loaded after ui.css)
 *   3. pass a `class` prop (appended to the component root)
 *   4. `wrnexus eject <name>` to copy the component into `app/components` and own it
 */

import { readdirSync, readFileSync } from "node:fs";
import { dirname, join } from "node:path";
import { fileURLToPath } from "node:url";

const here = dirname(fileURLToPath(import.meta.url));
const packageRoot = join(here, "..");
let cachedCss: string | undefined;
let cachedNames: string[] | undefined;

/** Absolute path to the directory of Wire UI component `.wrn` files. */
export function uiComponentsDir(): string {
  return join(packageRoot, "components");
}

/** Absolute path to the Wire UI stylesheet. */
export function uiCssPath(): string {
  return join(packageRoot, "ui.css");
}

/** The Wire UI stylesheet contents (all `.wire-*` classes, themed via tokens). */
export function uiCss(): string {
  return (cachedCss ??= readFileSync(uiCssPath(), "utf8"));
}

/** Names of the built-in components (e.g. for `wrnexus eject` listing). */
export function uiComponentNames(): string[] {
  cachedNames ??= readdirSync(uiComponentsDir())
    .filter((f) => f.endsWith(".wrn"))
    .map((f) => f.replace(/\.wrn$/, ""))
    .sort();
  return [...cachedNames];
}
