import { getLuminance } from '@mui/system/colorManipulator';

import { COLOR_TYPE } from './constants';
import { type ColorType } from './types';

export { COLOR_TYPE };
export type { ColorType };

const LUMINANCE_THRESHOLD = 0.4;

/** Returns 'light' or 'dark' based on the luminance of the given hex color. */
export const getColorType = (accentHex: string): ColorType =>
  getLuminance(accentHex) >= LUMINANCE_THRESHOLD
    ? COLOR_TYPE.light
    : COLOR_TYPE.dark;

type TokenizedPart = { text: string; isBold: boolean };

const TOKEN_SPLIT_REGEX = /(\{[^}]+\})/g;
const TOKEN_TEST_REGEX = /^\{[^}]+\}$/;

/** Splits text into plain and token (bold) segments for `{variable}` patterns. */
export const parseTokenizedText = (text: string): TokenizedPart[] =>
  text.split(TOKEN_SPLIT_REGEX).map(part => ({
    text: part,
    isBold: TOKEN_TEST_REGEX.test(part),
  }));
