import { themeTokens } from "../data/tokens.js";

const tokens = themeTokens;

const cssVar = (name: string) => `var(--${name})`;
const kebab = (value: string) => value.replace(/_/g, "-");
const dropPrefix = (value: string, prefix: string) =>
  value.startsWith(`${prefix}_`) ? value.slice(prefix.length + 1) : value;

export type ThemeColorPrimitiveKey = keyof typeof tokens.color.primitive;

export function colorPrimitiveHex(key: ThemeColorPrimitiveKey): string {
  return tokens.color.primitive[key];
}

export function colorPrimitiveVar(key: ThemeColorPrimitiveKey): string {
  return cssVar(`color-${kebab(key)}`);
}

export type ThemeSpacingPaddingKey = keyof typeof tokens.spacing.padding;
export type ThemeSpacingGapKey = keyof typeof tokens.spacing.gap;

export function spacingPaddingPx(key: ThemeSpacingPaddingKey): number {
  return tokens.spacing.padding[key];
}

export function spacingPaddingVar(key: ThemeSpacingPaddingKey): string {
  const suffix = kebab(dropPrefix(key, "padding"));
  return cssVar(`spacing-padding-${suffix}`);
}

export function spacingGapPx(key: ThemeSpacingGapKey): number {
  return tokens.spacing.gap[key];
}

export function spacingGapVar(key: ThemeSpacingGapKey): string {
  const suffix = kebab(dropPrefix(key, "gap"));
  return cssVar(`spacing-gap-${suffix}`);
}

export type ThemeLayoutBreakpointKey = keyof typeof tokens.layout.breakpoint;
export type ThemeLayoutSizeKey = keyof typeof tokens.layout.size;
export type ThemeLayoutRadiusSizeKey = keyof typeof tokens.layout.radius.size;
export type ThemeLayoutRadiusLevelKey = keyof typeof tokens.layout.radius.level;

export function layoutBreakpointPx(key: ThemeLayoutBreakpointKey): number {
  return tokens.layout.breakpoint[key];
}

export function layoutBreakpointVar(key: ThemeLayoutBreakpointKey): string {
  return cssVar(`theme-breakpoint-${kebab(key)}-start`);
}

export function layoutSizePx(key: ThemeLayoutSizeKey): number {
  return tokens.layout.size[key];
}

export function layoutSizeVar(key: ThemeLayoutSizeKey): string {
  return cssVar(`theme-size-${kebab(key)}`);
}

export function layoutRadiusSizePx(key: ThemeLayoutRadiusSizeKey): number {
  return tokens.layout.radius.size[key];
}

export function layoutRadiusSizeVar(key: ThemeLayoutRadiusSizeKey): string {
  const suffix = kebab(dropPrefix(key, "size"));
  return cssVar(`theme-radius-${suffix}`);
}

export function layoutRadiusLevelPx(key: ThemeLayoutRadiusLevelKey): number {
  return tokens.layout.radius.level[key];
}

export function layoutRadiusLevelVar(key: ThemeLayoutRadiusLevelKey): string {
  return cssVar(`theme-radius-${kebab(key)}`);
}

export type ThemeTypographyCategoryKey = keyof typeof tokens.typography;

export function typographyVariants(category: ThemeTypographyCategoryKey) {
  return tokens.typography[category];
}
