/**
 * Named-scheme resolution to hex swatches (docs/exploration/chart-theming-scope.md §5).
 *
 * Split from theme-controls.ts because of the `vega-scale` import below:
 * theme-controls is reachable from the landing/learn entry graphs (via
 * `vega-themes`), and a static vega-scale edge there drags the vega vendor
 * chunk into the marketing pages' eager JS (`scripts/check-light-entries.mjs`
 * guards this after every build). Only the app's color controls resolve
 * schemes to swatches, so the edge lives here, app-side of the split.
 */

import { scheme } from 'vega-scale';

/**
 * Resolve a named Vega scheme to hex swatches. A categorical scheme returns its
 * fixed palette in full; a continuous scheme (sequential/diverging) is sampled
 * at `count` evenly-spaced stops (`count` applies to continuous schemes only).
 * Continuous interpolators yield `rgb(...)`, normalized to hex here. An unknown
 * name returns `[]` — the picker shows that scheme without a preview rather than
 * throwing. Used for the swatch/gradient preview and "materialize to swatches".
 */
export function schemeColors(name: string, count = 9): string[] {
  const resolved: unknown = scheme(name);
  if (Array.isArray(resolved)) return resolved.map((c) => toHex(String(c)));
  if (typeof resolved === 'function' && count > 0) {
    const interp = resolved as (t: number) => string;
    if (count === 1) return [toHex(interp(0.5))];
    return Array.from({ length: count }, (_, i) => toHex(interp(i / (count - 1))));
  }
  return [];
}

/** Normalize a CSS color to `#rrggbb`; passes through existing hex and unknowns. */
function toHex(color: string): string {
  if (color.startsWith('#')) return color;
  const m = /rgba?\(\s*([\d.]+)\s*,\s*([\d.]+)\s*,\s*([\d.]+)/i.exec(color);
  if (!m) return color;
  const h = (n: string) => Math.round(Number(n)).toString(16).padStart(2, '0');
  return `#${h(m[1])}${h(m[2])}${h(m[3])}`;
}
