Skip to content

A lightweight Clip Studio Paint alternative with real-time multiplayer collaborative drawing. Built with Tauri and React.

58.4 KB
Raw Blame
import {
  ACCENT_PIGMENTS,
  APPEARANCE_LIMITS,
  AppearanceConfig,
  BuiltInLookPresetId,
  ChromeStyle,
  ColorScheme,
  CornerRadiusPreset,
  DEFAULT_APPEARANCE_CONFIG,
  DensityPreset,
  FontProfile,
  INK_THEME_FORMAT_ID,
  INK_THEME_SCHEMA_VERSION,
  InkThemePresetFile,
  LOOK_PRESETS,
  OklchColor,
  OverridableTokenKey,
  ParseThemePresetResult,
  ScrollbarSize,
  VALID_ACCENT_PIGMENTS,
  VALID_BRUSH_LIST_STYLES,
  VALID_BUILT_IN_LOOK_PRESETS,
  VALID_CANVAS_MATTE_MODES,
  VALID_CHROME_STYLES,
  VALID_CORNER_RADIUS_PRESETS,
  VALID_DENSITY_PRESETS,
  VALID_FONT_PROFILES,
  VALID_ICON_STROKE_WIDTHS,
  VALID_LAYER_THUMB_SIZES,
  VALID_LOOK_PRESETS,
  VALID_OVERRIDABLE_TOKEN_KEYS,
  VALID_SCROLLBAR_SIZES,
  VALID_SLIDER_STYLES,
  isValidOverrideColorValue,
  normalizeHex6,
  sanitizeAppearanceConfig,
} from '../types/appearance';
import { t } from '../i18n';

export interface RgbColor {
  r: number;
  g: number;
  b: number;
}

export interface SemanticTokenMap {
  // Surfaces
  '--ui-canvas-matte': string;
  '--ui-bg-void': string;
  '--ui-bg-panel': string;
  '--ui-bg-header': string;
  '--ui-bg-control': string;
  '--ui-bg-control-hover': string;
  '--ui-bg-control-active': string;
  '--ui-bg-input': string;
  '--ui-bg-elevated': string;
  '--ui-bg-floating': string;
  '--ui-bg-overlay': string;

  // Borders
  '--ui-border-subtle': string;
  '--ui-border-default': string;
  '--ui-border-strong': string;
  '--ui-border-focus': string;

  // Text & Icons
  '--ui-text-primary': string;
  '--ui-text-secondary': string;
  '--ui-text-muted': string;
  '--ui-text-disabled': string;
  '--ui-icon-default': string;
  '--ui-icon-muted': string;

  // Accent & Semantic States
  '--ui-accent': string;
  '--ui-accent-rgb': string;
  '--ui-accent-contrast': string;
  '--ui-accent-subtle': string;
  '--ui-accent-hover': string;
  '--ui-accent-border': string;
  '--ui-danger': string;
  '--ui-warning': string;
  '--ui-success': string;

  // Geometry, Spacing & Typography
  '--ui-radius-xs': string;
  '--ui-radius-sm': string;
  '--ui-radius-md': string;
  '--ui-radius-lg': string;
  '--ui-panel-gap': string;
  '--ui-panel-padding': string;
  '--ui-control-height': string;
  '--ui-row-height': string;
  '--ui-font-sans': string;
  '--ui-font-mono': string;
  '--ui-icon-stroke': string;
  '--ui-scrollbar-size': string;
  '--ui-floating-opacity': string;
  '--ui-shadow-floating': string;
  '--ui-shadow-popover': string;
}

export type SemanticTokenKey = keyof SemanticTokenMap;

export interface ContrastAuditReport {
  primaryOnPanel: number;
  primaryOnControl: number;
  mutedOnPanel: number;
  iconOnPanel: number;
  accentContrastOnAccent: number;
}

export interface ResolvedAppearanceTheme {
  config: AppearanceConfig;
  colorScheme: ColorScheme;
  tokens: SemanticTokenMap;
  contrast: ContrastAuditReport;
}

export interface ApplyAppearanceOptions {
  themePreset?: string;
  legacyAccent?: string;
}

// ============================================================================
// OKLCH <-> sRGB & WCAG 2.1 Color Math (Dependency-Free)
// ============================================================================

const DEG_TO_RAD = Math.PI / 180;
const RAD_TO_DEG = 180 / Math.PI;
const GAMUT_EPSILON = 1e-6;
const MAX_SURFACE_CHROMA = 0.018;

function clamp(value: number, min: number, max: number): number {
  if (!Number.isFinite(value)) return min;
  return value < min ? min : value > max ? max : value;
}

function linearToSrgbChannel(linear: number): number {
  const c = clamp(linear, 0, 1);
  if (c <= 0.0031308) {
    return 12.92 * c;
  }
  return 1.055 * Math.pow(c, 1 / 2.4) - 0.055;
}

function srgbChannelToLinear(channel255: number): number {
  const u = clamp(channel255 / 255, 0, 1);
  if (u <= 0.04045) {
    return u / 12.92;
  }
  return Math.pow((u + 0.055) / 1.055, 2.4);
}

function oklchToLinearRgbRaw(
  l: number,
  c: number,
  hDeg: number
): { r: number; g: number; b: number } {
  const rad = hDeg * DEG_TO_RAD;
  const a = c * Math.cos(rad);
  const b = c * Math.sin(rad);

  // Björn Ottosson Oklab -> LMS -> linear sRGB
  const lPrime = l + 0.3963377774 * a + 0.2158037573 * b;
  const mPrime = l - 0.1055613458 * a - 0.0638541728 * b;
  const sPrime = l - 0.0894841775 * a - 1.291485548 * b;

  const lmsL = lPrime * lPrime * lPrime;
  const lmsM = mPrime * mPrime * mPrime;
  const lmsS = sPrime * sPrime * sPrime;

  return {
    r: 4.0767416621 * lmsL - 3.3077115913 * lmsM + 0.2309699292 * lmsS,
    g: -1.2684380046 * lmsL + 2.6097574011 * lmsM - 0.3413193965 * lmsS,
    b: -0.0041960863 * lmsL - 0.7034186147 * lmsM + 1.707614701 * lmsS,
  };
}

function isInSrgbGamut(rgb: { r: number; g: number; b: number }): boolean {
  return (
    rgb.r >= -GAMUT_EPSILON &&
    rgb.r <= 1 + GAMUT_EPSILON &&
    rgb.g >= -GAMUT_EPSILON &&
    rgb.g <= 1 + GAMUT_EPSILON &&
    rgb.b >= -GAMUT_EPSILON &&
    rgb.b <= 1 + GAMUT_EPSILON
  );
}

/**
 * Converts OKLCH (L in [0,1], C >= 0, H in degrees) to sRGB [0..255] using
 * chroma-preserving gamut mapping when a requested chroma falls outside sRGB.
 */
export function oklchToRgb(l: number, c: number, h: number): RgbColor {
  const safeL = clamp(l, 0, 1);
  if (safeL <= 0) return { r: 0, g: 0, b: 0 };
  if (safeL >= 1) return { r: 255, g: 255, b: 255 };

  const safeC = clamp(c, 0, 0.5);
  const safeH = Number.isFinite(h) ? ((h % 360) + 360) % 360 : 0;

  let linear = oklchToLinearRgbRaw(safeL, safeC, safeH);

  // Gamut-map by binary searching chroma while preserving L and H
  if (safeC > 0 && !isInSrgbGamut(linear)) {
    let low = 0;
    let high = safeC;
    for (let i = 0; i < 14; i += 1) {
      const mid = (low + high) * 0.5;
      const probe = oklchToLinearRgbRaw(safeL, mid, safeH);
      if (isInSrgbGamut(probe)) {
        low = mid;
        linear = probe;
      } else {
        high = mid;
      }
    }
    if (!isInSrgbGamut(linear)) {
      linear = oklchToLinearRgbRaw(safeL, low, safeH);
    }
  }

  return {
    r: Math.round(linearToSrgbChannel(linear.r) * 255),
    g: Math.round(linearToSrgbChannel(linear.g) * 255),
    b: Math.round(linearToSrgbChannel(linear.b) * 255),
  };
}

export function rgbToHex(rgb: RgbColor): string {
  const toByte = (v: number) => clamp(Math.round(v), 0, 255).toString(16).padStart(2, '0');
  return `#${toByte(rgb.r)}${toByte(rgb.g)}${toByte(rgb.b)}`;
}

export function oklchToHex(l: number, c: number, h: number): string {
  return rgbToHex(oklchToRgb(l, c, h));
}

export function parseHexColor(hex: string): RgbColor | null {
  if (typeof hex !== 'string') return null;
  const clean = hex.trim().replace(/^#/, '');
  if (clean.length === 3 && /^[0-9a-fA-F]{3}$/.test(clean)) {
    return {
      r: parseInt(clean[0] + clean[0], 16),
      g: parseInt(clean[1] + clean[1], 16),
      b: parseInt(clean[2] + clean[2], 16),
    };
  }
  if (clean.length === 6 && /^[0-9a-fA-F]{6}$/.test(clean)) {
    return {
      r: parseInt(clean.slice(0, 2), 16),
      g: parseInt(clean.slice(2, 4), 16),
      b: parseInt(clean.slice(4, 6), 16),
    };
  }
  return null;
}

export function rgbToOklch(rgb: RgbColor): OklchColor {
  const r = srgbChannelToLinear(rgb.r);
  const g = srgbChannelToLinear(rgb.g);
  const b = srgbChannelToLinear(rgb.b);

  const lmsL = 0.4122214708 * r + 0.5363325363 * g + 0.0514459929 * b;
  const lmsM = 0.2119034982 * r + 0.6806995451 * g + 0.1073969566 * b;
  const lmsS = 0.0883024619 * r + 0.2817188376 * g + 0.6299787005 * b;

  const lPrime = Math.cbrt(lmsL);
  const mPrime = Math.cbrt(lmsM);
  const sPrime = Math.cbrt(lmsS);

  const l = 0.2104542553 * lPrime + 0.793617785 * mPrime - 0.0040720468 * sPrime;
  const a = 1.9779984951 * lPrime - 2.428592205 * mPrime + 0.4505937099 * sPrime;
  const okB = 0.0259040371 * lPrime + 0.7827717662 * mPrime - 0.808675766 * sPrime;

  const c = Math.sqrt(a * a + okB * okB);
  const h = c < 1e-7 ? 0 : ((Math.atan2(okB, a) * RAD_TO_DEG) + 360) % 360;

  return {
    l: clamp(l, 0, 1),
    c: Number.isFinite(c) ? c : 0,
    h: Number.isFinite(h) ? h : 0,
  };
}

export function hexToOklch(hex: string): OklchColor | null {
  const rgb = parseHexColor(hex);
  return rgb ? rgbToOklch(rgb) : null;
}

/**
 * WCAG 2.1 relative luminance in [0, 1].
 */
export function getRelativeLuminance(color: RgbColor | string): number {
  const rgb = typeof color === 'string' ? parseHexColor(color) : color;
  if (!rgb) return 0;
  const r = srgbChannelToLinear(rgb.r);
  const g = srgbChannelToLinear(rgb.g);
  const b = srgbChannelToLinear(rgb.b);
  return 0.2126 * r + 0.7152 * g + 0.0722 * b;
}

/**
 * WCAG 2.1 contrast ratio in [1, 21].
 */
export function getContrastRatio(fg: RgbColor | string, bg: RgbColor | string): number {
  const fgRgb = typeof fg === 'string' ? parseHexColor(fg) : fg;
  const bgRgb = typeof bg === 'string' ? parseHexColor(bg) : bg;
  if (!fgRgb || !bgRgb) return 1;

  const l1 = getRelativeLuminance(fgRgb);
  const l2 = getRelativeLuminance(bgRgb);
  const lighter = Math.max(l1, l2);
  const darker = Math.min(l1, l2);
  return (lighter + 0.05) / (darker + 0.05);
}

/**
 * Picks whichever candidate foreground (`darkCandidate` vs `lightCandidate`) yields higher
 * WCAG contrast against `bgColor`, escalating to `#000000` / `#ffffff` when mid-tone custom
 * backgrounds need full luminance headroom to guarantee >= 4.5:1 readability.
 */
export function pickHighContrastForeground(
  bgColor: RgbColor | string,
  darkCandidate = '#161616',
  lightCandidate = '#f2f2f2'
): string {
  const darkRatio = getContrastRatio(darkCandidate, bgColor);
  const lightRatio = getContrastRatio(lightCandidate, bgColor);
  if (Math.max(darkRatio, lightRatio) >= 4.5) {
    return darkRatio >= lightRatio ? darkCandidate : lightCandidate;
  }
  const pureBlackRatio = getContrastRatio('#000000', bgColor);
  const pureWhiteRatio = getContrastRatio('#ffffff', bgColor);
  return pureBlackRatio >= pureWhiteRatio ? '#000000' : '#ffffff';
}

// ============================================================================
// Contrast Guardrail & Surface Calibration
// ============================================================================

function surfaceChromaForLightness(baseChroma: number, l: number): number {
  if (baseChroma <= 0) return 0;
  const lowTaper = clamp(l / 0.14, 0, 1);
  const highTaper = clamp((1 - l) / 0.04, 0, 1);
  return baseChroma * Math.min(lowTaper, highTaper);
}

function minContrastAgainst(fg: RgbColor, backgrounds: readonly RgbColor[]): number {
  let minRatio = Infinity;
  for (const bg of backgrounds) {
    const ratio = getContrastRatio(fg, bg);
    if (ratio < minRatio) minRatio = ratio;
  }
  return Number.isFinite(minRatio) ? minRatio : 1;
}

/**
 * Adjusts a candidate OKLCH foreground color toward the active polarity pole (or flips to the
 * higher-contrast pole if needed) until it achieves at least `targetRatio` against every
 * surface in `backgrounds`.
 */
function enforceContrastGuardrail(
  initial: OklchColor,
  backgrounds: readonly RgbColor[],
  direction: 'lighter' | 'darker',
  targetRatio: number
): string {
  const initialRgb = oklchToRgb(initial.l, initial.c, initial.h);
  if (minContrastAgainst(initialRgb, backgrounds) >= targetRatio) {
    return rgbToHex(initialRgb);
  }

  // Slight buffer over target so 8-bit sRGB hex quantization never dips below targetRatio
  const searchGoal = targetRatio + 0.06;

  const searchTowardPole = (poleL: number): { hex: string; ratio: number } => {
    const poleRgb = oklchToRgb(poleL, 0, initial.h);
    const poleRatio = minContrastAgainst(poleRgb, backgrounds);
    if (poleRatio < targetRatio) {
      return { hex: rgbToHex(poleRgb), ratio: poleRatio };
    }

    let low = 0; // t=0 => initial
    let high = 1; // t=1 => pole
    let bestRgb = poleRgb;
    let bestRatio = poleRatio;

    for (let i = 0; i < 16; i += 1) {
      const t = (low + high) * 0.5;
      const candL = initial.l + (poleL - initial.l) * t;
      // Taper chroma as we approach pure white/black so maximum luminance range is reachable
      const candC = initial.c * (1 - t * 0.85);
      const candRgb = oklchToRgb(candL, candC, initial.h);
      const ratio = minContrastAgainst(candRgb, backgrounds);
      if (ratio >= searchGoal) {
        bestRgb = candRgb;
        bestRatio = ratio;
        high = t;
      } else {
        low = t;
      }
    }

    return { hex: rgbToHex(bestRgb), ratio: bestRatio };
  };

  const preferredPole = direction === 'lighter' ? 1 : 0;
  const fallbackPole = direction === 'lighter' ? 0 : 1;

  const preferred = searchTowardPole(preferredPole);
  if (preferred.ratio >= targetRatio) {
    return preferred.hex;
  }

  const fallback = searchTowardPole(fallbackPole);
  return fallback.ratio > preferred.ratio ? fallback.hex : preferred.hex;
}

function formatRgba(rgb: RgbColor, alpha: number): string {
  const a = Math.round(clamp(alpha, 0, 1) * 1000) / 1000;
  return `rgba(${rgb.r}, ${rgb.g}, ${rgb.b}, ${a})`;
}

// ============================================================================
// Geometry, Density & Typography Scale Tables
// ============================================================================

const RADIUS_SCALES: Record<
  CornerRadiusPreset,
  { xs: string; sm: string; md: string; lg: string }
> = {
  sharp: { xs: '1px', sm: '2px', md: '3px', lg: '4px' },
  machined: { xs: '3px', sm: '4px', md: '5px', lg: '8px' },
  soft: { xs: '4px', sm: '6px', md: '9px', lg: '12px' },
};

const DENSITY_SCALES: Record<
  DensityPreset,
  { panelPadding: string; controlHeight: string; rowHeight: string; islandsGap: string }
> = {
  compact: {
    panelPadding: '6px',
    controlHeight: '22px',
    rowHeight: '24px',
    islandsGap: '4px',
  },
  balanced: {
    panelPadding: '8px',
    controlHeight: '26px',
    rowHeight: '28px',
    islandsGap: '6px',
  },
  comfortable: {
    panelPadding: '12px',
    controlHeight: '30px',
    rowHeight: '34px',
    islandsGap: '8px',
  },
};

const FONT_STACKS: Record<FontProfile, { sans: string; mono: string }> = {
  system: {
    sans: 'Inter, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Hiragino Sans", "Hiragino Kaku Gothic ProN", "Yu Gothic UI", "Yu Gothic", "BIZ UDPGothic", "Meiryo", "Noto Sans JP", "Helvetica Neue", Arial, sans-serif',
    mono: '"JetBrains Mono", "Cascadia Code", "SF Mono", Consolas, "BIZ UDGothic", "Yu Gothic", "Meiryo", ui-monospace, monospace',
  },
  humanist: {
    sans: '"Plus Jakarta Sans", "Segoe UI Variable", "Segoe UI", -apple-system, BlinkMacSystemFont, "Hiragino Sans", "Hiragino Kaku Gothic ProN", "Yu Gothic UI", "Meiryo", "Noto Sans JP", Roboto, sans-serif',
    mono: '"IBM Plex Mono", "SF Mono", Consolas, "BIZ UDGothic", "Yu Gothic", "Meiryo", ui-monospace, monospace',
  },
  technical: {
    sans: '"IBM Plex Sans", "DIN Alternate", "Bahnschrift", "Segoe UI", -apple-system, "BIZ UDPGothic", "Hiragino Kaku Gothic ProN", "Yu Gothic UI", "Meiryo", "Noto Sans JP", sans-serif',
    mono: '"JetBrains Mono", "IBM Plex Mono", "Fira Code", Consolas, "BIZ UDGothic", "Yu Gothic", "Meiryo", ui-monospace, monospace',
  },
};

const SCROLLBAR_SIZE_SCALES: Record<ScrollbarSize, string> = {
  slim: '5px',
  standard: '9px',
  tablet: '13px',
  large: '16px',
};

function resolvePanelGap(chromeStyle: ChromeStyle, density: DensityPreset): string {
  if (chromeStyle === 'islands') {
    return DENSITY_SCALES[density].islandsGap;
  }
  return '1px';
}

// ============================================================================
// Core Semantic Token Resolver
// ============================================================================

/**
 * Deterministically computes the complete semantic OKLCH token map, color scheme, and WCAG
 * contrast report from an `AppearanceConfig`.
 */
export function resolveAppearanceTokens(rawConfig: AppearanceConfig): ResolvedAppearanceTheme {
  const config = sanitizeAppearanceConfig(rawConfig);
  const anchorId: BuiltInLookPresetId =
    config.lookPreset === 'custom'
      ? (config.baseLookPreset ?? 'graphite-atelier')
      : config.lookPreset;
  const anchor = LOOK_PRESETS[anchorId] ?? LOOK_PRESETS['graphite-atelier'];

  // 1. Resolve continuous brightness & polarity (avoiding unreadable mid-grey deadband)
  const brightnessOffset = (config.surfaceBrightness / 100) * 0.18;
  const rawPanelL = clamp(anchor.panelL + brightnessOffset, 0.08, 0.968);

  const colorScheme: ColorScheme =
    anchor.colorScheme === 'light'
      ? rawPanelL < 0.55
        ? 'dark'
        : 'light'
      : rawPanelL > 0.55
        ? 'light'
        : 'dark';

  const panelL =
    colorScheme === 'dark' ? clamp(rawPanelL, 0.08, 0.485) : clamp(rawPanelL, 0.64, 0.968);

  const contrast = config.surfaceContrast;
  const warmth = config.surfaceWarmth;
  const baseChroma =
    Math.abs(warmth) < 0.001 ? 0 : (Math.abs(warmth) / 100) * MAX_SURFACE_CHROMA;
  const surfaceHue = warmth > 0 ? anchor.warmHue : warmth < 0 ? anchor.coolHue : 0;

  const makeSurfaceRgb = (l: number): RgbColor =>
    oklchToRgb(l, surfaceChromaForLightness(baseChroma, l), surfaceHue);

  // 2. Compute strict 4-step material hierarchy (void -> panel -> control/recessed -> elevated)
  let voidL: number;
  let headerL: number;
  let inputL: number;
  let controlL: number;
  let controlHoverL: number;
  let controlActiveL: number;
  let elevatedL: number;

  if (colorScheme === 'dark') {
    voidL = clamp(panelL - 0.0435 * contrast, 0.03, Math.max(0.03, panelL - 0.018));
    headerL = clamp(
      panelL - 0.022 * contrast,
      voidL + 0.006,
      Math.max(voidL + 0.006, panelL - 0.008)
    );
    inputL = clamp(panelL - 0.034 * contrast, voidL, Math.max(voidL, panelL - 0.012));
    controlL = clamp(panelL + 0.028 * contrast, panelL + 0.014, 0.538);
    controlHoverL = clamp(panelL + 0.0495 * contrast, controlL + 0.01, 0.55);
    controlActiveL = clamp(panelL + 0.07 * contrast, controlHoverL + 0.01, 0.562);
    elevatedL = clamp(panelL + 0.042 * contrast, controlL + 0.006, 0.548);
  } else {
    voidL = clamp(panelL - 0.048 * contrast, 0.575, panelL - 0.022);
    headerL = clamp(panelL - 0.022 * contrast, voidL + 0.008, panelL - 0.008);
    controlL = clamp(panelL - 0.032 * contrast, 0.592, panelL - 0.015);
    controlHoverL = clamp(panelL - 0.052 * contrast, 0.58, controlL - 0.01);
    controlActiveL = clamp(panelL - 0.072 * contrast, 0.568, controlHoverL - 0.01);
    inputL = clamp(panelL + 0.028 * contrast, Math.min(0.98, panelL + 0.01), 0.982);
    elevatedL = clamp(panelL + 0.038 * contrast, Math.min(0.984, panelL + 0.014), 0.986);
  }

  let voidRgb = makeSurfaceRgb(voidL);
  let panelRgb = makeSurfaceRgb(panelL);
  let headerRgb = makeSurfaceRgb(headerL);
  let inputRgb = makeSurfaceRgb(inputL);
  let controlRgb = makeSurfaceRgb(controlL);
  const controlHoverRgb = makeSurfaceRgb(controlHoverL);
  const controlActiveRgb = makeSurfaceRgb(controlActiveL);
  let elevatedRgb = makeSurfaceRgb(elevatedL);

  // 3. Canvas matte surround (independent of docked UI if desired)
  let canvasMatteHex: string;
  switch (config.canvasMatteMode) {
    case 'neutral-dark':
      canvasMatteHex = '#161616';
      break;
    case 'neutral-mid':
      canvasMatteHex = '#757575';
      break;
    case 'neutral-light':
      canvasMatteHex = '#d4d4d4';
      break;
    case 'custom':
      canvasMatteHex = normalizeHex6(config.canvasMatteCustomHex, '#161616');
      break;
    case 'linked':
    default: {
      const matteL = clamp(anchor.canvasMatteL + brightnessOffset, 0.04, 0.92);
      canvasMatteHex = rgbToHex(makeSurfaceRgb(matteL));
      break;
    }
  }

  const floatingBg = formatRgba(elevatedRgb, config.floatingOpacity);
  const overlayBg =
    colorScheme === 'dark' ? 'rgba(8, 8, 10, 0.72)' : 'rgba(18, 18, 22, 0.42)';

  // 4. Calibrated borders (1px hairline seams scaled by borderCrispness, chromeStyle & contrast)
  const borderInk: RgbColor =
    colorScheme === 'dark' ? { r: 255, g: 255, b: 255 } : { r: 18, g: 18, b: 22 };
  const crispFactor = config.borderCrispness / 55;
  const chromeFactor =
    config.chromeStyle === 'flat' ? 0.45 : config.chromeStyle === 'islands' ? 1.12 : 1.0;
  const contrastFactor = 0.75 + ((contrast - 0.7) / 0.7) * 0.5;
  const borderMultiplier = crispFactor * chromeFactor * contrastFactor;

  const baseSubtleAlpha = colorScheme === 'dark' ? 0.065 : 0.075;
  const baseDefaultAlpha = colorScheme === 'dark' ? 0.115 : 0.13;
  const baseStrongAlpha = colorScheme === 'dark' ? 0.21 : 0.24;

  const borderSubtle = formatRgba(borderInk, clamp(baseSubtleAlpha * borderMultiplier, 0, 0.42));
  const borderDefault = formatRgba(borderInk, clamp(baseDefaultAlpha * borderMultiplier, 0, 0.52));
  const borderStrong = formatRgba(borderInk, clamp(baseStrongAlpha * borderMultiplier, 0, 0.68));

  // 5. Accent & Semantic state colors
  let accentHex: string;
  if (config.accent === 'custom') {
    accentHex = normalizeHex6(config.customAccentHex, '#e5e5e5');
  } else {
    const pigment = ACCENT_PIGMENTS[config.accent] ?? ACCENT_PIGMENTS.neutral;
    const tone = pigment[colorScheme];
    accentHex = oklchToHex(tone.l, tone.c, tone.h);
  }

  let accentRgb = parseHexColor(accentHex) ?? { r: 229, g: 229, b: 229 };
  let accentContrast = pickHighContrastForeground(accentRgb, '#161616', '#f2f2f2');
  let accentSubtle = formatRgba(accentRgb, colorScheme === 'dark' ? 0.14 : 0.12);
  let accentHover = formatRgba(accentRgb, colorScheme === 'dark' ? 0.22 : 0.18);
  let accentBorder = formatRgba(accentRgb, colorScheme === 'dark' ? 0.34 : 0.36);
  let borderFocus = formatRgba(accentRgb, colorScheme === 'dark' ? 0.58 : 0.62);

  // 6. Text & Icon hierarchy with automatic WCAG contrast guardrail
  const textDirection: 'lighter' | 'darker' = colorScheme === 'dark' ? 'lighter' : 'darker';
  const textChroma = baseChroma * 0.32;

  const computeTextAndSemanticTokens = (
    surfPanel: RgbColor,
    surfControl: RgbColor,
    surfInput: RgbColor,
    surfHeader: RgbColor,
    surfElevated: RgbColor
  ) => {
    const primarySurfaces = [surfPanel, surfControl, surfInput, surfHeader, surfElevated];
    const uiSurfaces = [surfPanel, surfControl, surfElevated];

    const primaryInitL = colorScheme === 'dark' ? 0.922 : 0.225;
    const secondaryInitL = colorScheme === 'dark' ? 0.785 : 0.365;
    const mutedInitL = colorScheme === 'dark' ? 0.635 : 0.485;
    const disabledInitL = colorScheme === 'dark' ? 0.455 : 0.64;
    const iconDefaultInitL = colorScheme === 'dark' ? 0.84 : 0.31;
    const iconMutedInitL = colorScheme === 'dark' ? 0.635 : 0.485;

    const textPrimary = enforceContrastGuardrail(
      { l: primaryInitL, c: textChroma, h: surfaceHue },
      primarySurfaces,
      textDirection,
      4.5
    );
    const textSecondary = enforceContrastGuardrail(
      { l: secondaryInitL, c: textChroma, h: surfaceHue },
      uiSurfaces,
      textDirection,
      4.5
    );
    const textMuted = enforceContrastGuardrail(
      { l: mutedInitL, c: textChroma, h: surfaceHue },
      uiSurfaces,
      textDirection,
      3.0
    );

    const disabledFloor = 2.15;
    let textDisabled = enforceContrastGuardrail(
      {
        l: disabledInitL,
        c: surfaceChromaForLightness(textChroma, disabledInitL),
        h: surfaceHue,
      },
      uiSurfaces,
      textDirection,
      disabledFloor
    );

    // Ensure disabled text stays visibly dimmer than muted text whenever luminance headroom allows
    // (including when surface tokenOverrides flip effective polarity).
    const mutedRgb = parseHexColor(textMuted);
    const disabledRgb = parseHexColor(textDisabled);
    if (mutedRgb && disabledRgb) {
      const mutedContrast = minContrastAgainst(mutedRgb, uiSurfaces);
      const disabledContrast = minContrastAgainst(disabledRgb, uiSurfaces);
      if (mutedContrast > disabledFloor + 0.15 && disabledContrast >= mutedContrast - 0.15) {
        const bgLightnesses = uiSurfaces.map((s) => rgbToOklch(s).l);
        const avgBgL = bgLightnesses.reduce((sum, l) => sum + l, 0) / bgLightnesses.length;
        const mutedL = rgbToOklch(mutedRgb).l;
        const effectiveDirection: 'lighter' | 'darker' =
          mutedL >= avgBgL ? 'lighter' : 'darker';
        const anchorBgL =
          effectiveDirection === 'lighter'
            ? Math.max(...bgLightnesses)
            : Math.min(...bgLightnesses);
        const recalibrated = enforceContrastGuardrail(
          {
            l: anchorBgL,
            c: surfaceChromaForLightness(textChroma, anchorBgL),
            h: surfaceHue,
          },
          uiSurfaces,
          effectiveDirection,
          disabledFloor
        );
        const recalibratedRgb = parseHexColor(recalibrated);
        if (recalibratedRgb) {
          const recalibratedContrast = minContrastAgainst(recalibratedRgb, uiSurfaces);
          if (recalibratedContrast >= disabledFloor && recalibratedContrast < mutedContrast) {
            textDisabled = recalibrated;
          }
        }
      }
    }

    const iconDefault = enforceContrastGuardrail(
      { l: iconDefaultInitL, c: textChroma, h: surfaceHue },
      uiSurfaces,
      textDirection,
      3.0
    );
    const iconMuted = enforceContrastGuardrail(
      { l: iconMutedInitL, c: textChroma, h: surfaceHue },
      uiSurfaces,
      textDirection,
      3.0
    );

    const dangerInit: OklchColor =
      colorScheme === 'dark' ? { l: 0.67, c: 0.16, h: 25 } : { l: 0.51, c: 0.17, h: 25 };
    const warningInit: OklchColor =
      colorScheme === 'dark' ? { l: 0.77, c: 0.13, h: 78 } : { l: 0.55, c: 0.13, h: 72 };
    const successInit: OklchColor =
      colorScheme === 'dark' ? { l: 0.73, c: 0.11, h: 150 } : { l: 0.49, c: 0.12, h: 150 };

    const danger = enforceContrastGuardrail(dangerInit, uiSurfaces, textDirection, 3.0);
    const warning = enforceContrastGuardrail(warningInit, uiSurfaces, textDirection, 3.0);
    const success = enforceContrastGuardrail(successInit, uiSurfaces, textDirection, 3.0);

    return {
      textPrimary,
      textSecondary,
      textMuted,
      textDisabled,
      iconDefault,
      iconMuted,
      danger,
      warning,
      success,
    };
  };

  let textTokens = computeTextAndSemanticTokens(
    panelRgb,
    controlRgb,
    inputRgb,
    headerRgb,
    elevatedRgb
  );

  // 7. Geometry, spacing, typography & shadows
  const radii = RADIUS_SCALES[config.cornerRadius];
  const densityMetrics = DENSITY_SCALES[config.density];
  const fonts = FONT_STACKS[config.fontProfile];
  const panelGap = resolvePanelGap(config.chromeStyle, config.density);

  const shadowFloating =
    colorScheme === 'dark'
      ? '0 8px 24px rgba(0, 0, 0, 0.48), 0 1px 2px rgba(0, 0, 0, 0.32)'
      : '0 6px 20px rgba(15, 15, 20, 0.12), 0 1px 3px rgba(15, 15, 20, 0.08)';
  const shadowPopover =
    colorScheme === 'dark'
      ? '0 14px 36px rgba(0, 0, 0, 0.58), 0 2px 6px rgba(0, 0, 0, 0.36)'
      : '0 12px 32px rgba(15, 15, 20, 0.16), 0 2px 6px rgba(15, 15, 20, 0.1)';

  const tokens: SemanticTokenMap = {
    '--ui-canvas-matte': canvasMatteHex,
    '--ui-bg-void': rgbToHex(voidRgb),
    '--ui-bg-panel': rgbToHex(panelRgb),
    '--ui-bg-header': rgbToHex(headerRgb),
    '--ui-bg-control': rgbToHex(controlRgb),
    '--ui-bg-control-hover': rgbToHex(controlHoverRgb),
    '--ui-bg-control-active': rgbToHex(controlActiveRgb),
    '--ui-bg-input': rgbToHex(inputRgb),
    '--ui-bg-elevated': rgbToHex(elevatedRgb),
    '--ui-bg-floating': floatingBg,
    '--ui-bg-overlay': overlayBg,

    '--ui-border-subtle': borderSubtle,
    '--ui-border-default': borderDefault,
    '--ui-border-strong': borderStrong,
    '--ui-border-focus': borderFocus,

    '--ui-text-primary': textTokens.textPrimary,
    '--ui-text-secondary': textTokens.textSecondary,
    '--ui-text-muted': textTokens.textMuted,
    '--ui-text-disabled': textTokens.textDisabled,
    '--ui-icon-default': textTokens.iconDefault,
    '--ui-icon-muted': textTokens.iconMuted,

    '--ui-accent': accentHex,
    '--ui-accent-rgb': `${accentRgb.r}, ${accentRgb.g}, ${accentRgb.b}`,
    '--ui-accent-contrast': accentContrast,
    '--ui-accent-subtle': accentSubtle,
    '--ui-accent-hover': accentHover,
    '--ui-accent-border': accentBorder,
    '--ui-danger': textTokens.danger,
    '--ui-warning': textTokens.warning,
    '--ui-success': textTokens.success,

    '--ui-radius-xs': radii.xs,
    '--ui-radius-sm': radii.sm,
    '--ui-radius-md': radii.md,
    '--ui-radius-lg': radii.lg,
    '--ui-panel-gap': panelGap,
    '--ui-panel-padding': densityMetrics.panelPadding,
    '--ui-control-height': densityMetrics.controlHeight,
    '--ui-row-height': densityMetrics.rowHeight,
    '--ui-font-sans': fonts.sans,
    '--ui-font-mono': fonts.mono,
    '--ui-icon-stroke': String(config.iconStrokeWidth),
    '--ui-scrollbar-size': SCROLLBAR_SIZE_SCALES[config.scrollbarSize] ?? SCROLLBAR_SIZE_SCALES.standard,
    '--ui-floating-opacity': String(config.floatingOpacity),
    '--ui-shadow-floating': shadowFloating,
    '--ui-shadow-popover': shadowPopover,
  };

  // 8. Apply power-user tokenOverrides cleanly & re-derive dependent values if not overridden
  const overrides = config.tokenOverrides;
  if (overrides) {
    let surfaceOverridden = false;

    for (const [key, val] of Object.entries(overrides) as Array<[OverridableTokenKey, string]>) {
      if (val && VALID_OVERRIDABLE_TOKEN_KEYS.has(key) && isValidOverrideColorValue(val)) {
        tokens[key] = val;
        if (
          key === '--ui-bg-panel' ||
          key === '--ui-bg-control' ||
          key === '--ui-bg-input' ||
          key === '--ui-bg-header' ||
          key === '--ui-bg-elevated'
        ) {
          surfaceOverridden = true;
        }
      }
    }

    // Re-sync derived accent tokens when `--ui-accent` is overridden with a hex value
    if (overrides['--ui-accent']) {
      const parsedAccent = parseHexColor(overrides['--ui-accent']);
      if (parsedAccent) {
        accentRgb = parsedAccent;
        tokens['--ui-accent-rgb'] = `${parsedAccent.r}, ${parsedAccent.g}, ${parsedAccent.b}`;
        if (!overrides['--ui-accent-contrast']) {
          accentContrast = pickHighContrastForeground(parsedAccent, '#161616', '#f2f2f2');
          tokens['--ui-accent-contrast'] = accentContrast;
        }
        if (!overrides['--ui-accent-subtle']) {
          accentSubtle = formatRgba(parsedAccent, colorScheme === 'dark' ? 0.14 : 0.12);
          tokens['--ui-accent-subtle'] = accentSubtle;
        }
        if (!overrides['--ui-accent-hover']) {
          accentHover = formatRgba(parsedAccent, colorScheme === 'dark' ? 0.22 : 0.18);
          tokens['--ui-accent-hover'] = accentHover;
        }
        if (!overrides['--ui-accent-border']) {
          accentBorder = formatRgba(parsedAccent, colorScheme === 'dark' ? 0.34 : 0.36);
          tokens['--ui-accent-border'] = accentBorder;
        }
        if (!overrides['--ui-border-focus']) {
          borderFocus = formatRgba(parsedAccent, colorScheme === 'dark' ? 0.58 : 0.62);
          tokens['--ui-border-focus'] = borderFocus;
        }
      }
    }

    // Protect text readability if a surface was overridden without explicitly overriding text
    if (surfaceOverridden) {
      panelRgb = parseHexColor(tokens['--ui-bg-panel']) ?? panelRgb;
      controlRgb = parseHexColor(tokens['--ui-bg-control']) ?? controlRgb;
      inputRgb = parseHexColor(tokens['--ui-bg-input']) ?? inputRgb;
      headerRgb = parseHexColor(tokens['--ui-bg-header']) ?? headerRgb;
      elevatedRgb = parseHexColor(tokens['--ui-bg-elevated']) ?? elevatedRgb;
      voidRgb = parseHexColor(tokens['--ui-bg-void']) ?? voidRgb;

      textTokens = computeTextAndSemanticTokens(
        panelRgb,
        controlRgb,
        inputRgb,
        headerRgb,
        elevatedRgb
      );
      if (!overrides['--ui-text-primary']) tokens['--ui-text-primary'] = textTokens.textPrimary;
      if (!overrides['--ui-text-secondary']) tokens['--ui-text-secondary'] = textTokens.textSecondary;
      if (!overrides['--ui-text-muted']) tokens['--ui-text-muted'] = textTokens.textMuted;
      if (!overrides['--ui-text-disabled']) tokens['--ui-text-disabled'] = textTokens.textDisabled;
      if (!overrides['--ui-icon-default']) tokens['--ui-icon-default'] = textTokens.iconDefault;
      if (!overrides['--ui-icon-muted']) tokens['--ui-icon-muted'] = textTokens.iconMuted;
      if (!overrides['--ui-danger']) tokens['--ui-danger'] = textTokens.danger;
      if (!overrides['--ui-warning']) tokens['--ui-warning'] = textTokens.warning;
      if (!overrides['--ui-success']) tokens['--ui-success'] = textTokens.success;
    }
  }

  const finalPanel = parseHexColor(tokens['--ui-bg-panel']) ?? panelRgb;
  const finalControl = parseHexColor(tokens['--ui-bg-control']) ?? controlRgb;
  const finalPrimaryText = parseHexColor(tokens['--ui-text-primary']) ?? { r: 229, g: 229, b: 229 };
  const finalMutedText = parseHexColor(tokens['--ui-text-muted']) ?? { r: 138, g: 138, b: 138 };
  const finalIcon = parseHexColor(tokens['--ui-icon-default']) ?? finalPrimaryText;
  const finalAccent = parseHexColor(tokens['--ui-accent']) ?? accentRgb;
  const finalAccentContrast = parseHexColor(tokens['--ui-accent-contrast']) ?? {
    r: 22,
    g: 22,
    b: 22,
  };

  return {
    config,
    colorScheme,
    tokens,
    contrast: {
      primaryOnPanel: getContrastRatio(finalPrimaryText, finalPanel),
      primaryOnControl: getContrastRatio(finalPrimaryText, finalControl),
      mutedOnPanel: getContrastRatio(finalMutedText, finalPanel),
      iconOnPanel: getContrastRatio(finalIcon, finalPanel),
      accentContrastOnAccent: getContrastRatio(finalAccentContrast, finalAccent),
    },
  };
}

// ============================================================================
// Zero-Rerender DOM Application (with per-element diff cache)
// ============================================================================

const appliedPropertyCache = new WeakMap<HTMLElement, Map<string, string>>();
const appliedAttrCache = new WeakMap<HTMLElement, Map<string, string>>();

function setStylePropCached(
  root: HTMLElement,
  cache: Map<string, string>,
  prop: string,
  value: string
): void {
  if (cache.get(prop) === value) return;
  root.style.setProperty(prop, value);
  cache.set(prop, value);
}

function setAttrCached(
  root: HTMLElement,
  cache: Map<string, string>,
  attr: string,
  value: string
): void {
  if (cache.get(attr) === value) return;
  root.setAttribute(attr, value);
  cache.set(attr, value);
}

/**
 * Applies all semantic `--ui-*` tokens, backward-compatible legacy aliases, and `data-*`
 * attributes directly to `root` (`document.documentElement`) without triggering React re-renders.
 */
export function applyAppearanceTokens(
  root: HTMLElement | null | undefined,
  config: AppearanceConfig,
  options?: ApplyAppearanceOptions
): ResolvedAppearanceTheme {
  const resolved = resolveAppearanceTokens(config);

  if (!root || !root.style || typeof root.style.setProperty !== 'function') {
    return resolved;
  }

  let propCache = appliedPropertyCache.get(root);
  if (!propCache) {
    propCache = new Map<string, string>();
    appliedPropertyCache.set(root, propCache);
  }

  let attrCache = appliedAttrCache.get(root);
  if (!attrCache) {
    attrCache = new Map<string, string>();
    appliedAttrCache.set(root, attrCache);
  }

  const { tokens, colorScheme, config: sanitized } = resolved;

  // Apply all semantic `--ui-*` CSS custom properties
  for (const [key, value] of Object.entries(tokens)) {
    setStylePropCached(root, propCache, key, value);
  }

  // Keep all legacy CSS variables 100% synchronized for backward compatibility
  const legacyAliases: Record<string, string> = {
    '--bg-canvas': tokens['--ui-bg-void'],
    '--bg-panel': tokens['--ui-bg-panel'],
    '--bg-hover': tokens['--ui-bg-control-hover'],
    '--text-primary': tokens['--ui-text-primary'],
    '--text-muted': tokens['--ui-text-muted'],
    '--accent': tokens['--ui-accent'],
    '--accent-rgb': tokens['--ui-accent-rgb'],
    '--accent-contrast': tokens['--ui-accent-contrast'],
    '--accent-subtle': tokens['--ui-accent-subtle'],
    '--accent-border': tokens['--ui-accent-border'],
    '--modern-accent': tokens['--ui-accent'],
    '--modern-accent-rgb': tokens['--ui-accent-rgb'],
    '--modern-accent-subtle': tokens['--ui-accent-subtle'],
    '--modern-accent-border': tokens['--ui-accent-border'],
    '--modern-accent-hover': tokens['--ui-accent-hover'],
    '--modern-accent-glow': 'transparent',
    '--modern-bg-base': tokens['--ui-bg-void'],
    '--modern-bg-surface': tokens['--ui-bg-panel'],
    '--modern-bg-elevated': tokens['--ui-bg-elevated'],
    '--modern-bg-input': tokens['--ui-bg-input'],
    '--modern-border': tokens['--ui-border-subtle'],
  };

  for (const [key, value] of Object.entries(legacyAliases)) {
    setStylePropCached(root, propCache, key, value);
  }

  // Apply root data attributes for CSS selectors & tooling
  if (typeof root.setAttribute === 'function') {
    setAttrCached(root, attrCache, 'data-color-scheme', colorScheme);
    setAttrCached(root, attrCache, 'data-look-preset', sanitized.lookPreset);
    setAttrCached(root, attrCache, 'data-chrome-style', sanitized.chromeStyle);
    setAttrCached(root, attrCache, 'data-density', sanitized.density);
    setAttrCached(root, attrCache, 'data-radius', sanitized.cornerRadius);
    setAttrCached(root, attrCache, 'data-slider-style', sanitized.sliderStyle);
    setAttrCached(root, attrCache, 'data-scrollbar-size', sanitized.scrollbarSize);
    setAttrCached(root, attrCache, 'data-theme', options?.themePreset ?? 'modern');
    setAttrCached(root, attrCache, 'data-accent', options?.legacyAccent ?? sanitized.accent);
  }

  return resolved;
}

/**
 * Convenience helper to apply appearance tokens directly to `document.documentElement` when running
 * in a browser environment.
 */
export function applyAppearanceToDocument(
  config: AppearanceConfig,
  options?: ApplyAppearanceOptions
): ResolvedAppearanceTheme {
  const root =
    typeof document !== 'undefined' && document.documentElement ? document.documentElement : null;
  return applyAppearanceTokens(root, config, options);
}

// ============================================================================
// .inktheme Export / Import Serialization & Strict Schema Validation
// ============================================================================

const MAX_THEME_FILE_BYTES = 64 * 1024;

export interface SerializeThemePresetMetadata {
  name?: string;
  author?: string;
  description?: string;
  createdAt?: string;
}

/**
 * Serializes an `AppearanceConfig` into a versioned `.inktheme` JSON string.
 */
export function serializeThemePreset(
  config: AppearanceConfig,
  metadata: SerializeThemePresetMetadata = {}
): string {
  const sanitized = sanitizeAppearanceConfig(config);
  const presetName =
    typeof metadata.name === 'string' && metadata.name.trim().length > 0
      ? metadata.name.trim().slice(0, 80)
      : sanitized.lookPreset === 'custom'
        ? 'Custom Studio Theme'
        : LOOK_PRESETS[sanitized.lookPreset].label;

  const payload: InkThemePresetFile = {
    format: INK_THEME_FORMAT_ID,
    version: INK_THEME_SCHEMA_VERSION,
    name: presetName,
    ...(typeof metadata.author === 'string' && metadata.author.trim()
      ? { author: metadata.author.trim().slice(0, 80) }
      : {}),
    ...(typeof metadata.description === 'string' && metadata.description.trim()
      ? { description: metadata.description.trim().slice(0, 280) }
      : {}),
    ...(typeof metadata.createdAt === 'string' && metadata.createdAt.trim()
      ? { createdAt: metadata.createdAt.trim().slice(0, 64) }
      : {}),
    appearance: sanitized,
  };

  return JSON.stringify(payload, null, 2);
}

/**
 * Parses and strictly validates a `.inktheme` JSON string. Rejects malformed, corrupted,
 * incompatible-version, or unsafe payloads without throwing.
 */
export function parseThemePreset(rawJson: string): ParseThemePresetResult {
  if (typeof rawJson !== 'string' || rawJson.trim().length === 0) {
    return { ok: false, error: t('Theme preset input is empty.') };
  }

  if (rawJson.length > MAX_THEME_FILE_BYTES) {
    return { ok: false, error: t('Theme preset file exceeds maximum allowed size (64 KB).') };
  }

  let parsed: unknown;
  try {
    parsed = JSON.parse(rawJson);
  } catch {
    return { ok: false, error: t('Theme preset is not valid JSON.') };
  }

  if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
    return { ok: false, error: t('Theme preset root must be a JSON object.') };
  }

  const root = parsed as Record<string, unknown>;

  if (root.format !== INK_THEME_FORMAT_ID) {
    return {
      ok: false,
      error: t('Invalid theme format identifier. Expected "{expected}".', {
        expected: INK_THEME_FORMAT_ID,
      }),
    };
  }

  if (root.version !== INK_THEME_SCHEMA_VERSION) {
    return {
      ok: false,
      error: t('Unsupported theme schema version: {version}. Expected version {expected}.', {
        version: String(root.version),
        expected: INK_THEME_SCHEMA_VERSION,
      }),
    };
  }

  if (typeof root.name !== 'string' || root.name.trim().length === 0) {
    return { ok: false, error: t('Theme preset must include a non-empty "name" string.') };
  }

  if (!root.appearance || typeof root.appearance !== 'object' || Array.isArray(root.appearance)) {
    return {
      ok: false,
      error: t('Theme preset must include an "appearance" configuration object.'),
    };
  }

  const app = root.appearance as Record<string, unknown>;
  const warnings: string[] = [];

  // Strict field validation on provided keys
  if (
    app.lookPreset !== undefined &&
    (typeof app.lookPreset !== 'string' ||
      !VALID_LOOK_PRESETS.has(app.lookPreset as AppearanceConfig['lookPreset']))
  ) {
    return {
      ok: false,
      error: t('Invalid lookPreset "{value}".', { value: String(app.lookPreset) }),
    };
  }

  if (
    app.baseLookPreset !== undefined &&
    (typeof app.baseLookPreset !== 'string' ||
      !VALID_BUILT_IN_LOOK_PRESETS.has(app.baseLookPreset as BuiltInLookPresetId))
  ) {
    return {
      ok: false,
      error: t('Invalid baseLookPreset "{value}".', { value: String(app.baseLookPreset) }),
    };
  }

  const numericChecks: Array<{
    field: keyof typeof APPEARANCE_LIMITS;
    min: number;
    max: number;
  }> = [
    { field: 'surfaceBrightness', ...APPEARANCE_LIMITS.surfaceBrightness },
    { field: 'surfaceContrast', ...APPEARANCE_LIMITS.surfaceContrast },
    { field: 'surfaceWarmth', ...APPEARANCE_LIMITS.surfaceWarmth },
    { field: 'borderCrispness', ...APPEARANCE_LIMITS.borderCrispness },
    { field: 'floatingOpacity', ...APPEARANCE_LIMITS.floatingOpacity },
  ];

  for (const { field, min, max } of numericChecks) {
    const val = app[field];
    if (val !== undefined) {
      if (typeof val !== 'number' || !Number.isFinite(val)) {
        return { ok: false, error: t('Field "{field}" must be a finite number.', { field }) };
      }
      if (val < min || val > max) {
        warnings.push(
          t('Clamped "{field}" from {val} into [{min}, {max}].', { field, val, min, max })
        );
      }
    }
  }

  if (
    app.canvasMatteMode !== undefined &&
    (typeof app.canvasMatteMode !== 'string' ||
      !VALID_CANVAS_MATTE_MODES.has(app.canvasMatteMode as AppearanceConfig['canvasMatteMode']))
  ) {
    return {
      ok: false,
      error: t('Invalid canvasMatteMode "{value}".', { value: String(app.canvasMatteMode) }),
    };
  }

  if (
    app.canvasMatteCustomHex !== undefined &&
    (typeof app.canvasMatteCustomHex !== 'string' ||
      !/^#([0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/.test(app.canvasMatteCustomHex.trim()))
  ) {
    return {
      ok: false,
      error: t('Field "canvasMatteCustomHex" must be a valid hex color.'),
    };
  }

  if (
    app.accent !== undefined &&
    (typeof app.accent !== 'string' ||
      !VALID_ACCENT_PIGMENTS.has(app.accent as AppearanceConfig['accent']))
  ) {
    return {
      ok: false,
      error: t('Invalid accent pigment "{value}".', { value: String(app.accent) }),
    };
  }

  if (
    app.customAccentHex !== undefined &&
    (typeof app.customAccentHex !== 'string' ||
      !/^#([0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/.test(app.customAccentHex.trim()))
  ) {
    return {
      ok: false,
      error: t('Field "customAccentHex" must be a valid hex color.'),
    };
  }

  if (
    app.cornerRadius !== undefined &&
    (typeof app.cornerRadius !== 'string' ||
      !VALID_CORNER_RADIUS_PRESETS.has(app.cornerRadius as CornerRadiusPreset))
  ) {
    return {
      ok: false,
      error: t('Invalid cornerRadius "{value}".', { value: String(app.cornerRadius) }),
    };
  }

  if (
    app.chromeStyle !== undefined &&
    (typeof app.chromeStyle !== 'string' || !VALID_CHROME_STYLES.has(app.chromeStyle as ChromeStyle))
  ) {
    return {
      ok: false,
      error: t('Invalid chromeStyle "{value}".', { value: String(app.chromeStyle) }),
    };
  }

  if (
    app.density !== undefined &&
    (typeof app.density !== 'string' || !VALID_DENSITY_PRESETS.has(app.density as DensityPreset))
  ) {
    return {
      ok: false,
      error: t('Invalid density "{value}".', { value: String(app.density) }),
    };
  }

  if (
    app.fontProfile !== undefined &&
    (typeof app.fontProfile !== 'string' || !VALID_FONT_PROFILES.has(app.fontProfile as FontProfile))
  ) {
    return {
      ok: false,
      error: t('Invalid fontProfile "{value}".', { value: String(app.fontProfile) }),
    };
  }

  if (
    app.iconStrokeWidth !== undefined &&
    (typeof app.iconStrokeWidth !== 'number' ||
      !VALID_ICON_STROKE_WIDTHS.has(app.iconStrokeWidth as AppearanceConfig['iconStrokeWidth']))
  ) {
    return {
      ok: false,
      error: t('Invalid iconStrokeWidth "{value}".', { value: String(app.iconStrokeWidth) }),
    };
  }

  if (
    app.sliderStyle !== undefined &&
    (typeof app.sliderStyle !== 'string' ||
      !VALID_SLIDER_STYLES.has(app.sliderStyle as AppearanceConfig['sliderStyle']))
  ) {
    return {
      ok: false,
      error: t('Invalid sliderStyle "{value}".', { value: String(app.sliderStyle) }),
    };
  }

  if (
    app.brushListStyle !== undefined &&
    (typeof app.brushListStyle !== 'string' ||
      !VALID_BRUSH_LIST_STYLES.has(app.brushListStyle as AppearanceConfig['brushListStyle']))
  ) {
    return {
      ok: false,
      error: t('Invalid brushListStyle "{value}".', { value: String(app.brushListStyle) }),
    };
  }

  if (
    app.layerThumbSize !== undefined &&
    (typeof app.layerThumbSize !== 'string' ||
      !VALID_LAYER_THUMB_SIZES.has(app.layerThumbSize as AppearanceConfig['layerThumbSize']))
  ) {
    return {
      ok: false,
      error: t('Invalid layerThumbSize "{value}".', { value: String(app.layerThumbSize) }),
    };
  }

  if (
    app.scrollbarSize !== undefined &&
    (typeof app.scrollbarSize !== 'string' ||
      !VALID_SCROLLBAR_SIZES.has(app.scrollbarSize as AppearanceConfig['scrollbarSize']))
  ) {
    return {
      ok: false,
      error: t('Invalid scrollbarSize "{value}".', { value: String(app.scrollbarSize) }),
    };
  }

  if (app.tokenOverrides !== undefined) {
    if (
      !app.tokenOverrides ||
      typeof app.tokenOverrides !== 'object' ||
      Array.isArray(app.tokenOverrides)
    ) {
      return {
        ok: false,
        error: t('Field "tokenOverrides" must be a plain key-value object.'),
      };
    }
    for (const [key, val] of Object.entries(app.tokenOverrides as Record<string, unknown>)) {
      if (!VALID_OVERRIDABLE_TOKEN_KEYS.has(key as OverridableTokenKey)) {
        return {
          ok: false,
          error: t('Unknown or non-overridable token key "{key}".', { key }),
        };
      }
      if (!isValidOverrideColorValue(val)) {
        return {
          ok: false,
          error: t('Invalid or unsafe color value for token "{key}".', { key }),
        };
      }
    }
  }

  const sanitizedAppearance = sanitizeAppearanceConfig({
    ...DEFAULT_APPEARANCE_CONFIG,
    ...app,
  });

  const preset: InkThemePresetFile = {
    format: INK_THEME_FORMAT_ID,
    version: INK_THEME_SCHEMA_VERSION,
    name: root.name.trim().slice(0, 80),
    ...(typeof root.author === 'string' && root.author.trim()
      ? { author: root.author.trim().slice(0, 80) }
      : {}),
    ...(typeof root.description === 'string' && root.description.trim()
      ? { description: root.description.trim().slice(0, 280) }
      : {}),
    ...(typeof root.createdAt === 'string' && root.createdAt.trim()
      ? { createdAt: root.createdAt.trim().slice(0, 64) }
      : {}),
    appearance: sanitizedAppearance,
  };

  return { ok: true, preset, warnings };
}

// ============================================================================
// Compact Shareable Theme Codes (Base64URL .inktheme) & Curated Harmonious Mixes
// ============================================================================

export const INK_THEME_CODE_PREFIX = 'INKTHEME1:' as const;

const BASE64_ALPHABET =
  'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';

function encodeBytesToBase64(bytes: Uint8Array): string {
  if (typeof btoa === 'function') {
    let binary = '';
    for (let i = 0; i < bytes.length; i += 1) {
      binary += String.fromCharCode(bytes[i]);
    }
    return btoa(binary);
  }
  let out = '';
  for (let i = 0; i < bytes.length; i += 3) {
    const b0 = bytes[i];
    const b1 = i + 1 < bytes.length ? bytes[i + 1] : 0;
    const b2 = i + 2 < bytes.length ? bytes[i + 2] : 0;
    const triple = (b0 << 16) | (b1 << 8) | b2;
    out += BASE64_ALPHABET[(triple >> 18) & 63];
    out += BASE64_ALPHABET[(triple >> 12) & 63];
    out += i + 1 < bytes.length ? BASE64_ALPHABET[(triple >> 6) & 63] : '=';
    out += i + 2 < bytes.length ? BASE64_ALPHABET[triple & 63] : '=';
  }
  return out;
}

function decodeBase64ToBytes(padded: string): Uint8Array | null {
  try {
    if (typeof atob === 'function') {
      const binary = atob(padded);
      const bytes = new Uint8Array(binary.length);
      for (let i = 0; i < binary.length; i += 1) {
        bytes[i] = binary.charCodeAt(i);
      }
      return bytes;
    }
    const clean = padded.replace(/=+$/, '');
    const out: number[] = [];
    for (let i = 0; i < clean.length; i += 4) {
      const c0 = BASE64_ALPHABET.indexOf(clean[i]);
      const c1 = BASE64_ALPHABET.indexOf(clean[i + 1]);
      const c2 = i + 2 < clean.length ? BASE64_ALPHABET.indexOf(clean[i + 2]) : -1;
      const c3 = i + 3 < clean.length ? BASE64_ALPHABET.indexOf(clean[i + 3]) : -1;
      if (c0 < 0 || c1 < 0) return null;
      out.push((c0 << 2) | (c1 >> 4));
      if (c2 >= 0) out.push(((c1 & 15) << 4) | (c2 >> 2));
      if (c3 >= 0) out.push(((c2 & 3) << 6) | c3);
    }
    return new Uint8Array(out);
  } catch {
    return null;
  }
}

function utf8ToBase64Url(input: string): string {
  const bytes = new TextEncoder().encode(input);
  return encodeBytesToBase64(bytes)
    .replace(/\+/g, '-')
    .replace(/\//g, '_')
    .replace(/=+$/g, '');
}

function base64UrlToUtf8(b64url: string): string | null {
  const normalized = b64url.replace(/-/g, '+').replace(/_/g, '/').replace(/\s+/g, '');
  if (!normalized || !/^[A-Za-z0-9+/]+={0,2}$/.test(normalized)) {
    return null;
  }
  const padLen = (4 - (normalized.length % 4)) % 4;
  const padded = normalized + '='.repeat(padLen);
  const bytes = decodeBase64ToBytes(padded);
  if (!bytes) return null;
  try {
    return new TextDecoder('utf-8', { fatal: true }).decode(bytes);
  } catch {
    return null;
  }
}

/**
 * Encodes an `AppearanceConfig` into a compact, Discord-friendly single-line share code
 * (`INKTHEME1:<base64url>`).
 */
export function encodeThemeShareCode(
  config: AppearanceConfig,
  metadata: SerializeThemePresetMetadata = {}
): string {
  const pretty = serializeThemePreset(config, metadata);
  const compactJson = JSON.stringify(JSON.parse(pretty));
  return `${INK_THEME_CODE_PREFIX}${utf8ToBase64Url(compactJson)}`;
}

/**
 * Decodes either a compact `INKTHEME1:<base64url>` share code OR raw `.inktheme` JSON,
 * routing everything through strict `parseThemePreset` validation.
 */
export function decodeThemeShareCode(rawInput: string): ParseThemePresetResult {
  if (typeof rawInput !== 'string') {
    return { ok: false, error: t('Theme code input must be a string.') };
  }

  // Strip surrounding whitespace and optional Discord markdown backticks / code fences
  let cleaned = rawInput.trim();
  if (cleaned.startsWith('```')) {
    cleaned = cleaned.replace(/^```[a-zA-Z0-9_-]*\s*/, '').replace(/\s*```$/, '').trim();
  } else if (cleaned.startsWith('`') && cleaned.endsWith('`') && cleaned.length >= 2) {
    cleaned = cleaned.slice(1, -1).trim();
  }

  if (cleaned.length === 0) {
    return { ok: false, error: t('Theme code is empty.') };
  }

  if (cleaned.length > MAX_THEME_FILE_BYTES) {
    return { ok: false, error: t('Theme code exceeds maximum allowed size (64 KB).') };
  }

  if (cleaned.toUpperCase().startsWith(INK_THEME_CODE_PREFIX)) {
    const encoded = cleaned.slice(INK_THEME_CODE_PREFIX.length).trim();
    const decodedJson = base64UrlToUtf8(encoded);
    if (!decodedJson) {
      return { ok: false, error: t('Theme code is corrupted or not valid base64.') };
    }
    return parseThemePreset(decodedJson);
  }

  if (cleaned.startsWith('{')) {
    return parseThemePreset(cleaned);
  }

  return {
    ok: false,
    error: t('Unrecognized theme code. Expected "{prefix}..." or .inktheme JSON.', {
      prefix: INK_THEME_CODE_PREFIX,
    }),
  };
}

export interface CuratedAppearanceMix {
  id: string;
  name: string;
  baseLookPreset: BuiltInLookPresetId;
  surfaceBrightness: number;
  surfaceContrast: number;
  surfaceWarmth: number;
  accent: AppearanceConfig['accent'];
  chromeStyle: ChromeStyle;
  cornerRadius: CornerRadiusPreset;
  canvasMatteMode: AppearanceConfig['canvasMatteMode'];
  borderCrispness: number;
}

/**
 * Curated, artist-grade combinations of tone + warmth + restrained pigment + chrome style.
 * Never produces garish random neon colors; every entry is WCAG-calibrated.
 */
export const CURATED_APPEARANCE_MIXES: readonly CuratedAppearanceMix[] = [
  {
    id: 'kyoto-sumi',
    name: 'Kyoto Sumi',
    baseLookPreset: 'sumi-sepia',
    surfaceBrightness: 4,
    surfaceContrast: 1.04,
    surfaceWarmth: 54,
    accent: 'vermilion',
    chromeStyle: 'hairline',
    cornerRadius: 'machined',
    canvasMatteMode: 'linked',
    borderCrispness: 58,
  },
  {
    id: 'architect-slate',
    name: 'Architect Slate',
    baseLookPreset: 'graphite-atelier',
    surfaceBrightness: -4,
    surfaceContrast: 1.08,
    surfaceWarmth: -26,
    accent: 'prussian',
    chromeStyle: 'hairline',
    cornerRadius: 'sharp',
    canvasMatteMode: 'neutral-dark',
    borderCrispness: 62,
  },
  {
    id: 'botanical-linen',
    name: 'Botanical Linen',
    baseLookPreset: 'warm-paper-light',
    surfaceBrightness: 0,
    surfaceContrast: 1.02,
    surfaceWarmth: 38,
    accent: 'matcha',
    chromeStyle: 'islands',
    cornerRadius: 'soft',
    canvasMatteMode: 'neutral-mid',
    borderCrispness: 56,
  },
  {
    id: 'nocturne-ochre',
    name: 'Nocturne Ochre',
    baseLookPreset: 'obsidian-oled',
    surfaceBrightness: 6,
    surfaceContrast: 1.08,
    surfaceWarmth: 18,
    accent: 'ochre',
    chromeStyle: 'islands',
    cornerRadius: 'machined',
    canvasMatteMode: 'neutral-dark',
    borderCrispness: 62,
  },
  {
    id: 'calibration-18',
    name: 'Calibration 18%',
    baseLookPreset: 'studio-neutral-18',
    surfaceBrightness: 0,
    surfaceContrast: 0.98,
    surfaceWarmth: 0,
    accent: 'neutral',
    chromeStyle: 'flat',
    cornerRadius: 'sharp',
    canvasMatteMode: 'neutral-mid',
    borderCrispness: 48,
  },
  {
    id: 'gallery-daylight',
    name: 'Gallery Daylight',
    baseLookPreset: 'daylight-crisp',
    surfaceBrightness: -6,
    surfaceContrast: 1.06,
    surfaceWarmth: -10,
    accent: 'prussian',
    chromeStyle: 'islands',
    cornerRadius: 'soft',
    canvasMatteMode: 'neutral-light',
    borderCrispness: 58,
  },
  {
    id: 'smoked-plum-atelier',
    name: 'Smoked Atelier',
    baseLookPreset: 'graphite-atelier',
    surfaceBrightness: -10,
    surfaceContrast: 1.04,
    surfaceWarmth: -14,
    accent: 'plum',
    chromeStyle: 'islands',
    cornerRadius: 'soft',
    canvasMatteMode: 'neutral-dark',
    borderCrispness: 54,
  },
  {
    id: 'washi-vermilion',
    name: 'Washi Seal',
    baseLookPreset: 'warm-paper-light',
    surfaceBrightness: -10,
    surfaceContrast: 1.05,
    surfaceWarmth: 62,
    accent: 'vermilion',
    chromeStyle: 'hairline',
    cornerRadius: 'machined',
    canvasMatteMode: 'linked',
    borderCrispness: 58,
  },
  {
    id: 'midnight-celadon',
    name: 'Midnight Celadon',
    baseLookPreset: 'obsidian-oled',
    surfaceBrightness: 8,
    surfaceContrast: 1.02,
    surfaceWarmth: -16,
    accent: 'matcha',
    chromeStyle: 'flat',
    cornerRadius: 'machined',
    canvasMatteMode: 'neutral-dark',
    borderCrispness: 52,
  },
  {
    id: 'drafting-ochre',
    name: 'Drafting Ochre',
    baseLookPreset: 'studio-neutral-18',
    surfaceBrightness: -14,
    surfaceContrast: 1.06,
    surfaceWarmth: 24,
    accent: 'ochre',
    chromeStyle: 'hairline',
    cornerRadius: 'machined',
    canvasMatteMode: 'neutral-mid',
    borderCrispness: 56,
  },
] as const;

function matchesCuratedMix(config: AppearanceConfig, mix: CuratedAppearanceMix): boolean {
  const currentBase =
    config.lookPreset === 'custom'
      ? (config.baseLookPreset ?? 'graphite-atelier')
      : config.lookPreset;
  return (
    currentBase === mix.baseLookPreset &&
    Math.abs(config.surfaceBrightness - mix.surfaceBrightness) <= 2 &&
    Math.abs(config.surfaceWarmth - mix.surfaceWarmth) <= 4 &&
    config.accent === mix.accent &&
    config.chromeStyle === mix.chromeStyle
  );
}

/**
 * Cycles cleanly to the next curated harmonious studio look while preserving ergonomic
 * workflow controls (density, font profile, icon weight, slider/brush/layer preferences).
 */
export function pickNextCuratedMix(
  current: AppearanceConfig,
  lastIndex = -1
): { index: number; name: string; appearance: AppearanceConfig } {
  const total = CURATED_APPEARANCE_MIXES.length;
  let chosenIdx = ((lastIndex + 1) % total + total) % total;

  for (let attempt = 0; attempt < total; attempt += 1) {
    const candidateIdx = (chosenIdx + attempt) % total;
    if (!matchesCuratedMix(current, CURATED_APPEARANCE_MIXES[candidateIdx])) {
      chosenIdx = candidateIdx;
      break;
    }
  }

  const mix = CURATED_APPEARANCE_MIXES[chosenIdx];
  const nextAppearance = sanitizeAppearanceConfig({
    ...current,
    lookPreset: 'custom',
    baseLookPreset: mix.baseLookPreset,
    surfaceBrightness: mix.surfaceBrightness,
    surfaceContrast: mix.surfaceContrast,
    surfaceWarmth: mix.surfaceWarmth,
    accent: mix.accent,
    chromeStyle: mix.chromeStyle,
    cornerRadius: mix.cornerRadius,
    canvasMatteMode: mix.canvasMatteMode,
    borderCrispness: mix.borderCrispness,
    tokenOverrides: undefined,
  });

  return { index: chosenIdx, name: mix.name, appearance: nextAppearance };
}

export type ContrastGradeTone = 'success' | 'warning' | 'danger';

export interface ContrastGrade {
  label: 'AAA' | 'AA' | 'AA Large' | 'Low';
  tone: ContrastGradeTone;
}

export function getContrastGrade(ratio: number): ContrastGrade {
  if (ratio >= 7.0) return { label: 'AAA', tone: 'success' };
  if (ratio >= 4.5) return { label: 'AA', tone: 'success' };
  if (ratio >= 3.0) return { label: 'AA Large', tone: 'warning' };
  return { label: 'Low', tone: 'danger' };
}