{% extends 'base.html' %}
{% block content %}
<section class="card">
  <h1>{{ t('rsvp') }}</h1>
  <p>{{ t('rsvp_members_intro') }}</p>
  <form method="post" class="form-grid">
    {% for member in members %}
    <article class="member-card" data-member-card>
      <h2 class="member-name">{{ member['name'] }}</h2>
      <div class="member-choice-row">
        <label class="radio-row">
          <input
            type="radio"
            name="attending_{{ member['id'] }}"
            value="yes"
            {% if member['attending'] == 1 %}checked{% endif %}
            data-attendance-input
            data-member-id="{{ member['id'] }}"
          />
          {{ t('attending') }}
        </label>

        <label class="radio-row">
          <input
            type="radio"
            name="attending_{{ member['id'] }}"
            value="no"
            {% if member['attending'] == 0 %}checked{% endif %}
            data-attendance-input
            data-member-id="{{ member['id'] }}"
          />
          {{ t('not_attending') }}
        </label>
      </div>

      {% if member['requires_age'] == 1 %}
      <label class="member-age-wrap" data-age-wrap data-member-id="{{ member['id'] }}">
        {{ t('member_age') }}
        <input
          type="number"
          min="0"
          max="17"
          step="1"
          name="age_{{ member['id'] }}"
          value="{{ member['child_age'] if member['child_age'] is not none else '' }}"
        />
        <small>{{ t('member_age_hint') }}</small>
      </label>
      {% endif %}
    </article>
    {% endfor %}

    <button class="btn" type="submit">{{ t('save') }}</button>
  </form>
</section>

<script>
  (() => {
    const inputs = Array.from(document.querySelectorAll("[data-attendance-input]"));
    const ageWraps = Array.from(document.querySelectorAll("[data-age-wrap]"));

    const updateAgeVisibility = () => {
      ageWraps.forEach((wrap) => {
        const memberId = wrap.getAttribute("data-member-id");
        const yesRadio = document.querySelector(`input[name="attending_${memberId}"][value="yes"]`);
        const ageInput = wrap.querySelector("input[type='number']");
        const shouldShow = Boolean(yesRadio && yesRadio.checked);
        wrap.classList.toggle("is-visible", shouldShow);
        if (ageInput) {
          ageInput.required = shouldShow;
          if (!shouldShow) {
            ageInput.value = "";
          }
        }
      });
    };

    inputs.forEach((input) => input.addEventListener("change", updateAgeVisibility));
    updateAgeVisibility();
  })();
</script>
{% endblock %}
