{% extends 'base.html' %}
{% block content %}
<section class="card form-card">
  <h1>{{ t('upload') }}</h1>
  <form method="post" enctype="multipart/form-data" class="form-grid">
    <label>
      {{ t('file') }}
      <input id="photo-input" type="file" name="photo" accept="image/jpeg,image/png,image/jpg,image/heic,image/heif,.heic,.heif" multiple />
    </label>
    <p class="upload-hint">{{ t('upload_multi_hint') }}</p>
    <div id="extra-file-inputs"></div>
    <button id="add-file-input" class="btn btn-ghost" type="button">{{ t('add_more_files') }}</button>
    <p id="upload-selected-count" class="upload-count"></p>
    <ul id="upload-file-list" class="upload-file-list"></ul>
    <button class="btn" type="submit">{{ t('upload_submit') }}</button>
  </form>
</section>

<script>
  (() => {
    const addBtn = document.getElementById("add-file-input");
    const extraInputs = document.getElementById("extra-file-inputs");
    const countEl = document.getElementById("upload-selected-count");
    const listEl = document.getElementById("upload-file-list");
    const countTpl = {{ t('upload_selected_count')|tojson }};

    const allInputs = () => Array.from(document.querySelectorAll('input[name="photo"]'));

    const createExtraInput = () => {
      const wrapper = document.createElement("label");
      wrapper.className = "extra-file-input";
      wrapper.textContent = {{ t('file')|tojson }};

      const input = document.createElement("input");
      input.type = "file";
      input.name = "photo";
      input.accept = "image/jpeg,image/png,image/jpg,image/heic,image/heif,.heic,.heif";
      input.required = false;
      input.addEventListener("change", renderSelection);

      wrapper.appendChild(input);
      extraInputs.appendChild(wrapper);
    };

    const renderSelection = () => {
      const names = [];
      allInputs().forEach((input) => {
        Array.from(input.files || []).forEach((file) => names.push(file.name));
      });

      if (!names.length) {
        countEl.textContent = "";
        listEl.innerHTML = "";
        return;
      }

      countEl.textContent = countTpl.replace("{count}", String(names.length));
      listEl.innerHTML = "";
      names.slice(0, 20).forEach((name) => {
        const item = document.createElement("li");
        item.textContent = name;
        listEl.appendChild(item);
      });
      if (names.length > 20) {
        const more = document.createElement("li");
        more.textContent = `+ ${names.length - 20} weitere`;
        listEl.appendChild(more);
      }
    };

    allInputs().forEach((input) => input.addEventListener("change", renderSelection));
    addBtn.addEventListener("click", () => {
      createExtraInput();
    });
  })();
</script>
{% endblock %}
