<div class="cal" id="cal-widget">
  <div class="cal__nav">
    <button class="cal__btn"
            hx-get="/api/log/days?month={{ prev_month }}{% if selected %}&selected={{ selected.isoformat() }}{% endif %}"
            hx-target="#cal-widget"
            hx-swap="outerHTML">&lsaquo;</button>
    <div class="cal__title">{{ month_name }} {{ year }}</div>
    <button class="cal__btn"
            hx-get="/api/log/days?month={{ next_month }}{% if selected %}&selected={{ selected.isoformat() }}{% endif %}"
            hx-target="#cal-widget"
            hx-swap="outerHTML">&rsaquo;</button>
  </div>
  <div class="cal__grid">
    <div class="cal__h">Mo</div>
    <div class="cal__h">Tu</div>
    <div class="cal__h">We</div>
    <div class="cal__h">Th</div>
    <div class="cal__h">Fr</div>
    <div class="cal__h">Sa</div>
    <div class="cal__h">Su</div>
    {% for week in grid %}
      {% for d in week %}
        {% if d is none %}
          <div class="cal__d cal__d--empty"></div>
        {% else %}
          {% set has_log = d in days_with_logs %}
          {% set is_selected = (selected and selected.day == d and selected.month == month and selected.year == year) %}
          {% set is_today = (today.day == d and today.month == month and today.year == year) %}
          {% set iso = "%04d-%02d-%02d" | format(year, month, d) %}
          <button class="cal__d
                        {% if has_log %}cal__d--has-log{% else %}cal__d--no-log{% endif %}
                        {% if is_selected %}cal__d--selected{% endif %}
                        {% if is_today %}cal__d--today{% endif %}"
                  {% if has_log %}
                  hx-get="/api/log/by-date/{{ iso }}?as=html"
                  hx-target="#log-content"
                  hx-swap="innerHTML"
                  hx-push-url="/log/{{ iso }}"
                  onclick="document.querySelectorAll('.cal__d--selected').forEach(b=>b.classList.remove('cal__d--selected'));this.classList.add('cal__d--selected')"
                  {% else %}
                  disabled
                  {% endif %}
          >{{ d }}</button>
        {% endif %}
      {% endfor %}
    {% endfor %}
  </div>
</div>
