/**
 * 循环动效速率档位（Skeleton / IconLoading 等共用）
 * 每档仅一个循环周期 duration；扫光 / 旋转共用基线。
 * TextShimmer 默认使用 TEXT_SHIMMER_SPEED_BASELINE（2100ms），慢于通用基线。
 * Button loading（.tfds-inline-spin）固定 --motion-inline-spin-loop（1s），不随档位切换。
 */

export const MOTION_SPEED_DURATION_META = {
  label: '循环周期',
  desc: '无限循环 loading 走完一圈 / 一次扫光的时长（非 hover 过渡）',
};

/**
 * 循环运行时 CSS 变量 — 默认引用基线档 --motion-speed-{baseline}；speed prop 注入覆盖
 */
export const MOTION_RUNTIME_VAR_BINDINGS = [
  { runtime: '--motion-icon-spin-loop', usedBy: 'IconLoading 渐变环', preview: 'icon-spin', source: 'duration' },
  { runtime: '--motion-skeleton-loop', usedBy: 'Skeleton 骨条扫光', preview: 'skeleton-shimmer', source: 'duration' },
  { runtime: '--motion-text-shimmer-loop', usedBy: 'TextShimmer 文字扫光', preview: 'text-shimmer', source: 'duration' },
];

/** theme.css 注册的循环 @keyframes（实现层，非速率 token） */
export const MOTION_CYCLE_KEYFRAMES = [
  { name: 'tfds-icon-rotate', usedBy: 'IconLoading', property: 'transform', preview: 'icon-spin', kind: 'loop', durationVar: '--motion-icon-spin-loop' },
  { name: 'tfds-skeleton-shimmer', usedBy: 'Skeleton', property: 'background-position', preview: 'skeleton-shimmer', kind: 'loop', durationVar: '--motion-skeleton-loop' },
  { name: 'tfds-text-shimmer', usedBy: 'TextShimmer', property: 'background-position', preview: 'text-shimmer', kind: 'loop', durationVar: '--motion-text-shimmer-loop' },
];

/** 六档按循环周期从快到慢；id = duration 毫秒数 */
export const TOKEN_MOTION_SPEED = {
  600: { label: '600ms', duration: '600ms' },
  900: { label: '900ms', duration: '900ms' },
  1200: { label: '1200ms', duration: '1200ms' },
  1500: { label: '1500ms', duration: '1500ms' },
  1800: { label: '1800ms', duration: '1800ms' },
  2100: { label: '2100ms', duration: '2100ms' },
};

/** 最快 → 最慢 */
export const MOTION_SPEED_IDS = ['600', '900', '1200', '1500', '1800', '2100'];

/** theme / 组件未指定 speed 时的基线档 */
export const MOTION_SPEED_BASELINE = '1200';

/** TextShimmer 未指定 speed 时的基线档（最慢档，标签扫光更易读） */
export const TEXT_SHIMMER_SPEED_BASELINE = '2100';

export const MOTION_SPEED_DEFAULT = TOKEN_MOTION_SPEED[MOTION_SPEED_BASELINE];
export const TEXT_SHIMMER_SPEED_DEFAULT = TOKEN_MOTION_SPEED[TEXT_SHIMMER_SPEED_BASELINE];

/** @param {string} raw */
export function parseMotionDurationMs(raw) {
  const s = String(raw || '').trim();
  if (!s) return 0;
  if (s.endsWith('ms')) return Number.parseFloat(s) || 0;
  if (s.endsWith('s')) {
    const n = Number.parseFloat(s);
    return Number.isFinite(n) ? n * 1000 : 0;
  }
  return Number.parseFloat(s) || 0;
}

/** @param {string} raw */
export function formatMotionDurationMsLabel(raw) {
  const ms = parseMotionDurationMs(raw);
  if (!ms) return String(raw || '');
  return `${Math.round(ms)}ms`;
}

/** @param {{ id?: string, duration?: string }} tier */
export function resolveTierDuration(tier) {
  return tier.duration || `${tier.id}ms`;
}

/** @param {string} [speedId] */
export function resolveMotionSpeedTier(speedId) {
  const key = speedId && TOKEN_MOTION_SPEED[speedId] ? speedId : MOTION_SPEED_BASELINE;
  return { id: key, ...TOKEN_MOTION_SPEED[key] };
}

/** @param {string} tierId */
export function motionSpeedTierCssVar(tierId) {
  return `--motion-speed-${tierId}`;
}

/** tier → 组件运行时 CSS 变量（speed prop 注入用） */
export function mapMotionSpeedTierToRuntimeVars(tier) {
  const duration = resolveTierDuration(tier);
  return {
    '--motion-skeleton-loop': duration,
    '--motion-icon-spin-loop': duration,
    '--motion-text-shimmer-loop': duration,
  };
}

/** @theme 基线档：运行时变量引用 --motion-speed-{baseline}；TextShimmer 单独引用 2100ms 档 */
export function buildDefaultMotionRuntimeVarRefs() {
  const base = MOTION_SPEED_BASELINE;
  const textShimmerBase = TEXT_SHIMMER_SPEED_BASELINE;
  const durationRef = `var(--motion-speed-${base})`;
  const textShimmerRef = `var(--motion-speed-${textShimmerBase})`;
  return {
    '--motion-skeleton-loop': durationRef,
    '--motion-icon-spin-loop': durationRef,
    '--motion-text-shimmer-loop': textShimmerRef,
  };
}

export function buildMotionSpeedSegOptions() {
  return MOTION_SPEED_IDS.map((id) => {
    const tier = TOKEN_MOTION_SPEED[id];
    return { id, label: tier.label };
  });
}

export function createMotionSpeedPreviewControl({ defaultSpeed = MOTION_SPEED_BASELINE } = {}) {
  return {
    id: 'speed',
    label: '速率',
    type: 'seg',
    options: buildMotionSpeedSegOptions(),
    default: defaultSpeed,
  };
}

/** TextShimmer 规范页预览：默认 2100ms */
export function createTextShimmerSpeedPreviewControl() {
  return createMotionSpeedPreviewControl({ defaultSpeed: TEXT_SHIMMER_SPEED_BASELINE });
}

/** 仅注入 TextShimmer 循环周期变量 */
export function getTextShimmerSpeedCssVar(speedId = TEXT_SHIMMER_SPEED_BASELINE) {
  return {
    '--motion-text-shimmer-loop': resolveTierDuration(resolveMotionSpeedTier(speedId)),
  };
}

/** @deprecated 等同 createMotionSpeedPreviewControl */
export function createIconLoadingSpeedPreviewControl() {
  return createMotionSpeedPreviewControl();
}

/** 将速率档位解析为可注入预览区 / 组件容器的 CSS 变量 */
export function getMotionSpeedCssVars(speedId = MOTION_SPEED_BASELINE) {
  return mapMotionSpeedTierToRuntimeVars(resolveMotionSpeedTier(speedId));
}

/** @deprecated 请用 createMotionSpeedPreviewControl() */
export const MOTION_SPEED_PREVIEW_CONTROL = createMotionSpeedPreviewControl();

/** 合并预览区 layout + 速率变量 */
export function getMotionPreviewAreaStyle(controlValues = {}, layout = {}) {
  return {
    ...getMotionSpeedCssVars(controlValues.speed),
    ...layout,
  };
}

/**
 * 属性面板 — 当前速率档位
 * @param {string} [speedId]
 */
export function buildMotionSpeedTokenGroup(speedId = MOTION_SPEED_BASELINE) {
  const t = resolveMotionSpeedTier(speedId);
  const duration = resolveTierDuration(t);
  return [
    { label: '档位', value: t.label, readOnly: true },
    {
      label: MOTION_SPEED_DURATION_META.label,
      cssProp: 'animation-duration',
      token: motionSpeedTierCssVar(t.id),
      value: duration,
      hint: MOTION_SPEED_DURATION_META.desc,
    },
  ];
}
