/**
 * Übungspositionen aus GET /api/training-units/:id für die Modul-Erstellung (Reihenfolge = Timeline).
 * @param {object} unit – hydratisierte Trainingseinheit mit `phases` und/oder `sections`
 * @returns {Array<{ exercise_id: number, exercise_variant_id: number|null, planned_duration_min: number|null, notes: string|null, exercise_title?: string, contextLabel: string }>}
 */
export function collectExercisePlacementsForModule(unit) {
  if (!unit || typeof unit !== 'object') return []

  const rows = []

  const pushFromSection = (sec, ctx) => {
    const st = (sec?.title || '').trim()
    for (const it of sec?.items || []) {
      if ((it?.item_type || 'exercise') !== 'exercise') continue
      const eid = it.exercise_id
      if (!eid) continue
      const labelParts = [ctx, st].filter(Boolean)
      rows.push({
        exercise_id: Number(eid),
        exercise_variant_id:
          it.exercise_variant_id != null && it.exercise_variant_id !== ''
            ? Number(it.exercise_variant_id)
            : null,
        planned_duration_min:
          it.planned_duration_min != null && it.planned_duration_min !== ''
            ? Number(it.planned_duration_min)
            : null,
        notes: it.notes != null && String(it.notes).trim() ? String(it.notes).trim() : null,
        exercise_title: (it.exercise_title || '').trim() || `Übung #${eid}`,
        contextLabel: labelParts.length ? labelParts.join(' · ') : '',
      })
    }
  }

  const phases = Array.isArray(unit.phases) ? unit.phases : []
  for (const ph of phases) {
    const pk = String(ph?.phase_kind || '').toLowerCase()
    const phaseCtx = (ph?.title || '').trim()
    if (pk === 'parallel') {
      for (const st of ph.streams || []) {
        const streamCtx = [phaseCtx, (st?.title || '').trim()].filter(Boolean).join(' · ')
        for (const sec of st?.sections || []) {
          pushFromSection(sec, streamCtx)
        }
      }
    } else {
      for (const sec of ph?.sections || []) {
        pushFromSection(sec, phaseCtx)
      }
    }
  }

  if (!rows.length && Array.isArray(unit.sections)) {
    for (const sec of unit.sections) {
      pushFromSection(sec, '')
    }
  }

  return rows
}
