{{ define "strings/fragments/formBody" }}
<div class="flex flex-col md:flex-row md:items-center gap-2">
  <input
    type="text"
    name="title"
    placeholder="Title..."
    value="{{ with .String.Title }}{{ . }}{{ end }}"
    class="md:max-w-64"
  >
  <input
    type="text"
    name="description"
    placeholder="Description ..."
    value="{{ with .String.Description }}{{ . }}{{ end }}"
    class="flex-1"
  >
</div>
<div id="string-files">
  {{ range .FileParams }}
    {{ template "strings/fragments/fileEdit" . }}
  {{ end }}
</div>
<div class="flex justify-between items-center">
  <div id="error"></div>
  <div class="flex gap-2">
    <!-- TODO: accept multiple files in a string
    <button
      type="button"
      class="w-fit btn rounded py-0"
      hx-get="/strings/fileEdit"
      hx-swap="beforeend"
      hx-target="#string-files"
      hx-indicator="this"
    >
      <span class="inline-flex items-center gap-2">
        {{ i "file-plus" "w-4 h-4" }}
        Add file
      </span>
    </button>
    -->
    <button
      type="submit"
      class="w-fit btn-create group"
    >
      <span class="inline-flex items-center gap-2">
        {{ i "arrow-up" "w-4 h-4" }}
        Publish
      </span>
      <span class="pl-2 hidden group-[.htmx-request]:inline">
        {{ i "loader-circle" "w-4 h-4 animate-spin" }}
      </span>
    </button>
  </div>
</div>
<script>
  (() => {
    const container = document.getElementById('string-files');

    // update file stats
    function updateStats(editor) {
      console.log('update stats');
      const textarea = editor.querySelector('textarea');
      const lineCount = editor.querySelector('#line-count');
      const byteCount = editor.querySelector('#byte-count');

      if (!textarea || !lineCount || !byteCount) return;

      const content = textarea.value;
      const lines = content === '' ? 0 : content.split('\n').length;
      const bytes = new TextEncoder().encode(content).length;

      lineCount.textContent = `${lines} line${lines !== 1 ? 's' : ''}`;
      byteCount.textContent = `${bytes} byte${bytes !== 1 ? 's' : ''}`;
    }

    function findEditorFromEvent(evt) {
      const textarea = evt.target.closest('#file-editor textarea');
      if (!textarea) return null;
      return textarea.closest('#file-editor');
    }
    container.addEventListener('input', (evt) => {
      const editor = findEditorFromEvent(evt);
      if (!editor) return;
      updateStats(editor);
    });
    container.addEventListener('paste', (evt) => {
      const editor = findEditorFromEvent(evt);
      if (!editor) return;
      setTimeout(() => updateStats(editor), 0);
    });

    container.querySelectorAll('#file-editor').forEach((el) => {
      updateStats(el);
    });

    // disable remove-file-btn
    function updateRemoveButtons() {
      const editors = container.querySelectorAll('#file-editor');
      const buttons = container.querySelectorAll('#file-editor #remove-file-btn');
      if (editors.length == 1) {
        buttons.forEach(btn => { btn.disabled = true; });
      } else {
        buttons.forEach(btn => { btn.disabled = false; });
      }
    }

    (new MutationObserver(() => updateRemoveButtons())).observe(container, {
      childList: true,
      subtree: false,
    });
    updateRemoveButtons();

    // Because textarea triggering the keydown event can be added to DOM
    // after the initial load, we manually trigger the event from js.
    const form = document.querySelector('string-form');
    container.addEventListener('keydown', (evt) => {
      const textarea = evt.target.closest('#file-editor textarea');
      if (!textarea) return;
      if ((evt.ctrlKey || evt.metaKey) && evt.key === 'Enter') {
        htmx.trigger('#string-form', "ctrlenter");
      }
    });
  })();
</script>
{{ end }}
