/**
 * Parse asset mention spans directly from a DOM element (real-time, no stale state).
 * Use this when you have access to the editor DOM element.
 */
export function parseAssetMentionsFromDOM(el: HTMLElement): {
  counts: { image: number; video: number; audio: number };
  durations: { video: number; audio: number };
} {
  const counts = { image: 0, video: 0, audio: 0 };
  const durations = { video: 0, audio: 0 };
  el.querySelectorAll('[data-ref-type="asset"]').forEach((span) => {
    const t = (span as HTMLElement).dataset.assetType || 'Image';
    const rawDur = parseFloat((span as HTMLElement).dataset.duration || '0');
    const dur = isNaN(rawDur) ? 0 : rawDur;
    if (t === 'Video') { counts.video++; durations.video += dur; }
    else if (t === 'Audio') { counts.audio++; durations.audio += dur; }
    else { counts.image++; }
  });
  return { counts, durations };
}

/**
 * Parse asset mention spans from editor HTML string.
 * Use this when you only have the HTML string (e.g., from store state).
 */
export function parseAssetMentions(html: string): {
  counts: { image: number; video: number; audio: number };
  durations: { video: number; audio: number };
} {
  const counts = { image: 0, video: 0, audio: 0 };
  const durations = { video: 0, audio: 0 };
  if (!html) return { counts, durations };
  const parser = new DOMParser();
  const doc = parser.parseFromString(html, 'text/html');
  doc.querySelectorAll('[data-ref-type="asset"]').forEach((el) => {
    const t = (el as HTMLElement).dataset.assetType || 'Image';
    const rawDur = parseFloat((el as HTMLElement).dataset.duration || '0');
    const dur = isNaN(rawDur) ? 0 : rawDur;  // null/undefined → NaN → 0, ffprobe 失败不计入时长
    if (t === 'Video') { counts.video++; durations.video += dur; }
    else if (t === 'Audio') { counts.audio++; durations.audio += dur; }
    else { counts.image++; }
  });
  return { counts, durations };
}
