{% load i18n admin_urls form_extras %}
<div class="js-inline-admin-formset inline-group"
     id="{{ inline_admin_formset.formset.prefix }}-group"
     data-inline-type="stacked"
     data-inline-prefix="{{ inline_admin_formset.formset.prefix }}"
     data-inline-formset="{{ inline_admin_formset.inline_formset_data }}">
<fieldset class="module {{ inline_admin_formset.classes }}" aria-labelledby="{{ inline_admin_formset.formset.prefix }}-heading">
  <style>
    [data-inline-prefix="{{ inline_admin_formset.formset.prefix }}"] .inline-deletelink,
    [data-inline-prefix="{{ inline_admin_formset.formset.prefix }}"] .form-row.field-DELETE,
    [data-inline-prefix="{{ inline_admin_formset.formset.prefix }}"] .fieldBox.field-DELETE {
      display: none !important;
    }

    [data-inline-prefix="{{ inline_admin_formset.formset.prefix }}"] .profile-inline-heading {
      display: flex;
      align-items: center;
      gap: 0.75rem;
      flex-wrap: wrap;
    }

    [data-inline-prefix="{{ inline_admin_formset.formset.prefix }}"] .profile-inline-heading__title {
      display: flex;
      align-items: center;
      gap: 0.35rem;
      flex-wrap: wrap;
    }

    [data-inline-prefix="{{ inline_admin_formset.formset.prefix }}"] .profile-inline-heading__user-datum {
      margin-left: auto;
      display: flex;
      align-items: center;
      gap: 0.35rem;
      color: var(--body-quiet-color);
      font-weight: 400;
      text-decoration: none;
    }

    [data-inline-prefix="{{ inline_admin_formset.formset.prefix }}"] .profile-inline-heading__user-datum span {
      display: flex;
      align-items: center;
      gap: 0.35rem;
    }

    [data-inline-prefix="{{ inline_admin_formset.formset.prefix }}"] .profile-inline-heading__user-datum input {
      margin: 0;
    }

    [data-inline-prefix="{{ inline_admin_formset.formset.prefix }}"] .profile-inline-heading__user-datum a {
      color: inherit;
    }

    [data-inline-prefix="{{ inline_admin_formset.formset.prefix }}"] .profile-fieldset-visibility {
      display: block;
    }

    [data-inline-prefix="{{ inline_admin_formset.formset.prefix }}"] .is-hidden-by-visibility {
      display: none !important;
    }

  </style>
  {% if inline_admin_formset.is_collapsible %}<details><summary>{% endif %}
  <h2 id="{{ inline_admin_formset.formset.prefix }}-heading" class="inline-heading">
  {% if inline_admin_formset.formset.max_num == 1 %}
    {{ inline_admin_formset.opts.verbose_name|capfirst }}
  {% else %}
    {{ inline_admin_formset.opts.verbose_name_plural|capfirst }}
  {% endif %}
  </h2>
  {% if inline_admin_formset.is_collapsible %}</summary>{% endif %}
{{ inline_admin_formset.formset.management_form }}
{{ inline_admin_formset.formset.non_form_errors }}

{% for inline_admin_form in inline_admin_formset %}<div class="inline-related{% if inline_admin_form.original or inline_admin_form.show_url %} has_original{% endif %}{% if forloop.last and inline_admin_formset.has_add_permission %} empty-form last-related{% endif %}" id="{{ inline_admin_formset.formset.prefix }}-{% if forloop.last and inline_admin_formset.has_add_permission %}empty{% else %}{{ forloop.counter0 }}{% endif %}">
  <h3 class="inline-related-heading profile-inline-heading">
    <span class="profile-inline-heading__title">
      <b>{{ inline_admin_formset.opts.verbose_name|capfirst }}:</b>
      <span class="inline_label">{% if inline_admin_form.original %}{{ inline_admin_form.original }}{% if inline_admin_form.model_admin.show_change_link and inline_admin_form.model_admin.has_registered_model %} <a href="{% url inline_admin_form.model_admin.opts|admin_urlname:'change' inline_admin_form.original.pk|admin_urlquote %}" class="{{ inline_admin_formset.has_change_permission|yesno:'inlinechangelink,inlineviewlink' }}">{% if inline_admin_formset.has_change_permission %}{% translate "Change" %}{% else %}{% translate "View" %}{% endif %}</a>{% endif %}{% else %}#{{ forloop.counter }}{% endif %}</span>
      {% if inline_admin_form.show_url %}<a href="{{ inline_admin_form.absolute_url }}">{% translate "View on site" %}</a>{% endif %}
      {% if inline_admin_formset.formset.can_delete and inline_admin_formset.has_delete_permission %}{{ inline_admin_form.deletion_field.field.as_hidden }}{% endif %}
    </span>
    {% if inline_admin_form.form.fields.user_datum %}
    {% with user_datum_field=inline_admin_form.form.user_datum %}
    <label for="{{ user_datum_field.id_for_label }}" class="profile-inline-heading__user-datum">
      {{ user_datum_field.as_widget }}
      <span>{% trans "User Datum" %} [ <a href="{% url 'admin:user_data' %}">{% trans "View" %}</a> ]</span>
    </label>
    {% endwith %}
    {% endif %}
  </h3>
  {% if inline_admin_form.form.non_field_errors %}{{ inline_admin_form.form.non_field_errors }}{% endif %}

  {% with parent_counter=forloop.counter0 %}
    {% for fieldset in inline_admin_form %}
      {% resolve_fieldset_visibility fieldset inline_admin_form.model_admin.fieldset_visibility as fieldset_visibility %}
      {% if fieldset_visibility %}
        <div class="profile-fieldset-visibility"
             data-visibility-field="{{ fieldset_visibility.field }}"
             {% if fieldset_visibility.mode %}data-visibility-mode="{{ fieldset_visibility.mode }}"{% endif %}
             {% if fieldset_visibility.values %}data-visibility-values="{{ fieldset_visibility.values|join:' ' }}"{% endif %}>
          {% include "admin/includes/fieldset.html" with heading_level=4 prefix=fieldset.formset.prefix id_prefix=parent_counter id_suffix=forloop.counter0 %}
        </div>
      {% else %}
        {% include "admin/includes/fieldset.html" with heading_level=4 prefix=fieldset.formset.prefix id_prefix=parent_counter id_suffix=forloop.counter0 %}
      {% endif %}
    {% endfor %}
  {% endwith %}

  {% if inline_admin_form.needs_explicit_pk_field %}{{ inline_admin_form.pk_field.field }}{% endif %}
  {% if inline_admin_form.fk_field %}{{ inline_admin_form.fk_field.field }}{% endif %}
</div>{% endfor %}
  {% if inline_admin_formset.is_collapsible %}</details>{% endif %}
</fieldset>
</div>
<script>
  (function () {
    const group = document.getElementById("{{ inline_admin_formset.formset.prefix }}-group");
    if (!group || group.dataset.visibilityInitialized === "true") {
      return;
    }
    group.dataset.visibilityInitialized = "true";

    const HIDDEN_CLASS = "is-hidden-by-visibility";

    function parseValues(valueAttr) {
      if (!valueAttr) {
        return [];
      }
      return valueAttr.split(/\s+/).filter(Boolean);
    }

    function getInputs(container, fieldName) {
      const selector = `[name$="-${fieldName}"]`;
      const matches = Array.from(container.querySelectorAll(selector));
      if (!matches.length) {
        return [];
      }
      if (matches[0].type === "radio") {
        return matches;
      }
      return [matches[0]];
    }

    function currentValue(inputs) {
      if (!inputs.length) {
        return "";
      }
      const input = inputs[0];
      if (input.tagName === "SELECT") {
        return input.value;
      }
      if (input.type === "radio") {
        const checked = inputs.find((node) => node.checked);
        return checked ? checked.value : "";
      }
      if (input.type === "checkbox") {
        return input.checked ? "true" : "false";
      }
      return input.value;
    }

    function attachController(inline, fieldName, wrappers) {
      const inputs = getInputs(inline, fieldName);
      if (!inputs.length) {
        return;
      }

      const update = () => {
        const value = currentValue(inputs);
        wrappers.forEach((wrapper) => {
          const values = parseValues(wrapper.dataset.visibilityValues || "");
          const mode = (wrapper.dataset.visibilityMode || "show").toLowerCase();
          const matches = !values.length || values.includes(value);
          const shouldShow = mode === "hide" ? !matches : matches;
          wrapper.classList.toggle(HIDDEN_CLASS, !shouldShow);
        });
      };

      inputs.forEach((input) => {
        const handler = () => update();
        input.addEventListener("change", handler);
        if (
          input.tagName !== "SELECT" &&
          input.type !== "radio" &&
          input.type !== "checkbox"
        ) {
          input.addEventListener("input", handler);
        }
      });

      update();
    }

    function initializeInline(inline) {
      if (!inline || inline.dataset.visibilityInitialized === "true") {
        return;
      }

      const wrappers = Array.from(
        inline.querySelectorAll("[data-visibility-field]")
      );

      if (!wrappers.length) {
        inline.dataset.visibilityInitialized = "true";
        return;
      }

      const grouped = new Map();

      wrappers.forEach((wrapper) => {
        const fieldName = wrapper.dataset.visibilityField;
        if (!fieldName) {
          return;
        }
        if (!grouped.has(fieldName)) {
          grouped.set(fieldName, []);
        }
        grouped.get(fieldName).push(wrapper);
      });

      grouped.forEach((wrapperList, fieldName) => {
        attachController(inline, fieldName, wrapperList);
      });

      inline.dataset.visibilityInitialized = "true";
    }

    group.querySelectorAll(".inline-related").forEach((inline) => {
      initializeInline(inline);
    });

    document.addEventListener("formset:added", (event) => {
      if (
        !event.detail ||
        event.detail.formsetName !== "{{ inline_admin_formset.formset.prefix }}"
      ) {
        return;
      }
      const row = event.target;
      if (row && group.contains(row)) {
        if (row.dataset.visibilityInitialized === "true") {
          delete row.dataset.visibilityInitialized;
        }
        initializeInline(row);
      }
    });
  })();
</script>
