/**
 * TextShimmer — B 端纯文字扫光动效（标签级 loading 文案）
 *
 * 视觉对齐 Cursor ui-text-roll：三段渐变、2100ms 默认循环、200% 扫光带。
 *
 * **何时用**：AI 生成摘要、思考中、文档扫描、助手回复组装等「文案本身就是 loading 表面」的场景。
 * **不用**：区块结构占位 → Skeleton；所有渐变环 loading（含行内 pending）→ IconLoading。
 *
 * @prop {React.ReactNode} children — 扫光文案（宜短，单行 truncate）
 * @prop {'sm'|'md'|'lg'} [size='md'] — 字号档位 text-xs / text-sm / text-base
 * @prop {'sm'|'md'|'lg'} [spread='md'] — 高光带宽度（background-size）
 * @prop {typeof MOTION_SPEED_IDS[number]} [speed=TEXT_SHIMMER_SPEED_BASELINE] — 循环速率档位（见 TOKEN_MOTION_SPEED，默认 2100ms）
 * @prop {string} [duration] — 高级：直接覆盖循环周期（优先于 speed）
 * @prop {string} [baseColor] — 扫光源色（默认 text-tertiary；内部转为 60% 透明 muted）
 * @prop {string} [shimmerColor] — 扫光峰值色（默认 text-secondary；可传任意色值）
 * @prop {boolean} [animated=true] — 是否播放扫光
 * @prop {string} [className=''] — 附加类名（深色底可用 text-inherit 继承前景色）
 */

import {
  getTextShimmerSpeedCssVar,
  TEXT_SHIMMER_SPEED_BASELINE,
  MOTION_SPEED_IDS,
} from '../motion-speed.js';
import {
  TEXT_SHIMMER_HIGHLIGHT_VAR,
  TEXT_SHIMMER_MUTED_VAR,
  TEXT_SHIMMER_SOURCE_VAR,
  TEXT_SHIMMER_SPREAD_VAR,
} from '../text-shimmer.js';

const SIZE_CLASS = {
  sm: 'text-xs leading-4',
  md: 'text-sm leading-5',
  lg: 'text-base leading-6',
};

const SPREAD_VAR = {
  sm: '180%',
  md: '200%',
  lg: '240%',
};

const MUTED_MIX = (source) => `color-mix(in srgb, ${source} 60%, transparent)`;

function resolveShimmerSource(baseColor, className) {
  if (baseColor) return baseColor;
  if (/\btext-brand-/.test(className)) return 'var(--color-primary)';
  return null;
}

function usesCurrentColor(className) {
  return /\btext-inherit\b/.test(className);
}

export default function TextShimmer({
  children,
  size = 'md',
  spread = 'md',
  speed = TEXT_SHIMMER_SPEED_BASELINE,
  duration,
  baseColor,
  shimmerColor,
  animated = true,
  className = '',
  style: previewStyle,
  ...rest
}) {
  const sizeKey = SIZE_CLASS[size] ? size : 'md';
  const spreadKey = SPREAD_VAR[spread] ? spread : 'md';
  const onCurrentColor = usesCurrentColor(className);
  const shimmerSource = resolveShimmerSource(baseColor, className);

  const style = {
    ...(shimmerSource ? { [TEXT_SHIMMER_SOURCE_VAR]: shimmerSource } : {}),
    ...(shimmerSource
      ? { [TEXT_SHIMMER_MUTED_VAR]: MUTED_MIX(shimmerSource) }
      : {}),
    ...(onCurrentColor
      ? {
          [TEXT_SHIMMER_MUTED_VAR]: MUTED_MIX('currentColor'),
          [TEXT_SHIMMER_HIGHLIGHT_VAR]: shimmerColor || 'currentColor',
        }
      : {}),
    ...(spreadKey !== 'md' ? { [TEXT_SHIMMER_SPREAD_VAR]: SPREAD_VAR[spreadKey] } : {}),
    ...(duration
      ? { '--motion-text-shimmer-loop': duration }
      : speed && speed !== TEXT_SHIMMER_SPEED_BASELINE
        ? getTextShimmerSpeedCssVar(speed)
        : {}),
    ...(shimmerColor && !onCurrentColor
      ? { [TEXT_SHIMMER_HIGHLIGHT_VAR]: shimmerColor }
      : {}),
    ...(shimmerSource === 'var(--color-primary)' && !shimmerColor
      ? { [TEXT_SHIMMER_HIGHLIGHT_VAR]: 'var(--color-primary)' }
      : {}),
  };

  return (
    <span
      data-tfds-component="TextShimmer"
      role="status"
      aria-live="polite"
      className={[
        'tfds-text-shimmer inline-block max-w-full truncate align-middle',
        animated ? '' : 'tfds-text-shimmer--static',
        SIZE_CLASS[sizeKey],
        className,
      ].filter(Boolean).join(' ')}
      style={{ ...style, ...previewStyle }}
      {...rest}
    >
      {children}
    </span>
  );
}
