Help on script repeat for each with dynamic list

Hi,
I’m trying to write a script that will perform an action in parallel for a dynamic list of entities.
So far I couldn’t get the for_each to work using the documentation and reading posts.
Can it be done? Any advice?

area_on:
  alias: Switch area on
  mode: single
  fields:
    area:
      description: Name of the area
      example: woonkamer or 'woonkamer,keuken'
  variables:
    entities: "{{ area.split(',') | map('area_entities') | list | sum(start=[]) }}"
    lights: "{{ expand(states.light)|selectattr('entity_id', 'in', entities)|selectattr('state','ne','unavailable')|map(attribute='entity_id')|list }}"
    media_player: "{{ expand(states.media_player)|selectattr('entity_id', 'in', entities)|selectattr('state','ne','unavailable')|selectattr('attributes.device_class','eq','speaker')|map(attribute='entity_id')|first }}"
  sequence:
    - parallel:
      - repeat:
          for_each: "{{ lights }}"
          sequence:
             - service: light.turn_on
               target:
                 entity_id: "{{ repeat.item }}"
      - if:
        - condition: template
          value_template: "{{ states(media_player) != 'playing' }}"
        then:
          - service: script.sonos_play
            data:
              player: "{{ media_player }}"

What does the trace show?

One issue I can see is that there may be media_player entities that don’t have a defined device class, so you should select for that before selecting for it being “speaker”. I would also alter the variable definitions to start from entities and selecting by the domain string instead of starting with the full state objects of all light and all media player entities

lights: "{{ entities | select('match', 'light.') | select('has_value') | list }}"
media_player: |
  {{ expand( entities | select('match', 'media_player.') 
  | select('has_value'))  | selectattr('attributes.device_class', 'defined')
  | selectattr('attributes.device_class','eq','speaker') 
  | map(attribute='entity_id') | first }}

As i tried many things including namespace, I can’t quite recall the exact errors.
They all were complaining about the for each not being properly set.

Currently I have the script running without the repeat and just provide ‘lights’ to the light on action. This works but then the lights are switched off in sequence taking quite a while 1-4 sec.

Properly set with messages either showing:
all entities as a string joined with ’ - ’
or message that a list was expected but got str.