/**
 * Intl.Segmenter 策略（优先）
 *
 * 注意：不同 JS 引擎/版本对 Intl.Segmenter 的支持可能不同，调用方必须捕获异常并降级。
 */

export function canUseIntlSegmenter(): boolean {
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  const Seg = (globalThis as any)?.Intl?.Segmenter;
  return typeof Seg === 'function';
}

export function segmentWithIntlSegmenter(text: string): string[] {
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  const Segmenter = (globalThis as any).Intl.Segmenter as new (locales?: string | string[], options?: any) => any;

  // 用 zh-Hant 仅用于选择合适的 locale；grapheme 分割应与语言本身关系不大，但保持固定输入更易对齐跨端。
  const seg = new Segmenter('zh-Hant', { granularity: 'grapheme' });
  const it = seg.segment(text);

  const clusters: string[] = [];
  for (const part of it) {
    // part: { segment: string, index: number, input: string, isWordLike?: boolean }
    clusters.push(part.segment);
  }
  return clusters;
}

