{{ define "repo/fragments/editLabelPanel" }}
  <form
    id="edit-label-panel"
    hx-put="/{{ .RepoInfo.FullName }}/labels/perform"
    hx-indicator="#spinner"
    hx-disabled-elt="#save-btn,#cancel-btn"
    hx-swap="none"
    class="flex flex-col gap-6"
    >
    <input type="hidden" name="repo" value="{{ .RepoInfo.RepoAt }}">
    <input type="hidden" name="subject" value="{{ .Subject }}">
    {{ template "editBasicLabels" . }}
    {{ template "editKvLabels" . }}
    {{ template "editLabelPanelActions" . }}
    <div id="add-label-error" class="text-red-500 dark:text-red-400"></div>
  </form>
{{ end }}

{{ define "editBasicLabels" }}
  {{ $defs := .Defs }}
  {{ $subject := .Subject }}
  {{ $state := .State }}
  {{ $prefix := .Prefix }}
  {{ $labelStyle := "flex items-center gap-2 rounded py-1 px-2 border border-gray-200 dark:border-gray-700 text-sm bg-white dark:bg-gray-800 text-black dark:text-white" }}
  {{ $hasNullDefs := false }}
  {{ range $k, $d := $defs }}
    {{ if $d.ValueType.IsNull }}{{ $hasNullDefs = true }}{{ end }}
  {{ end }}
  <div>
    {{ template "repo/fragments/labelSectionHeaderText" "Labels" }}

    <div class="flex flex-col gap-1 items-start">
      {{ range $k, $d := $defs }}
        {{ if $d.ValueType.IsNull }}
          {{ $isChecked := $state.ContainsLabel $k }}
          {{ $fieldName := $d.AtUri.String }}
          {{ if $prefix }}{{ $fieldName = printf "%s[%s]" $prefix $d.AtUri }}{{ end }}
          <label class="{{$labelStyle}}">
            <input type="checkbox" name="{{ $fieldName }}" value="null" {{if $isChecked}}checked{{end}}>
            {{ template "labels/fragments/labelDef" $d }}
          </label>
        {{ end }}
      {{ end }}
      {{ if not $hasNullDefs }}
        <p class="text-gray-500 dark:text-gray-400 text-sm py-1">
          No labels defined. You can choose default labels or define custom
          labels in <a class="underline" href="/{{ $.RepoInfo.FullName }}/settings">settings</a>.
        </p>
      {{ end }}
    </div>
  </div>
{{ end }}

{{ define "editKvLabels" }}
  {{ $defs := .Defs }}
  {{ $subject := .Subject }}
  {{ $state := .State }}
  {{ $prefix := .Prefix }}
  {{ $groupSuffix := "" }}
  {{ if $prefix }}{{ $groupSuffix = printf "-%s" $prefix }}{{ end }}
  {{ $labelStyle := "font-normal normal-case flex items-center gap-2 p-0" }}

  {{ range $k, $d := $defs }}
    {{ if (not $d.ValueType.IsNull) }}
      {{ $fieldName := $d.AtUri.String }}
      {{ if $prefix }}{{ $fieldName = printf "%s[%s]" $prefix $d.AtUri }}{{ end }}
      {{ $valset := $state.GetValSet $k }}
      <div id="label-{{$d.Id}}{{ $groupSuffix }}" class="flex flex-col gap-1">
        {{ if not $d.ValueType.IsBool }}
          {{ template "repo/fragments/labelSectionHeaderText" $d.Name }}
        {{ end }}
          {{ if (and $d.Multiple $d.ValueType.IsEnum) }}
            <!-- checkbox -->
            {{ range $variant := $d.ValueType.Enum }}
              <label class="{{$labelStyle}}">
                <input type="checkbox" name="{{ $fieldName }}" value="{{$variant}}" {{if $state.ContainsLabelAndVal $k $variant}}checked{{end}}>
                {{ $variant }}
              </label>
            {{ end }}
          {{ else if $d.Multiple }}
            <!-- dynamically growing input fields -->
            {{ range $v, $s := $valset }}
              {{ template "multipleInputField" (dict "def" $d "value" $v "key" $k "prefix" $prefix) }}
            {{ else }}
              {{ template "multipleInputField" (dict "def" $d "value" "" "key" $k "prefix" $prefix) }}
            {{ end }}
            {{ template "addFieldButton" (dict "def" $d "prefix" $prefix "groupSuffix" $groupSuffix) }}
            {{ if and $.LoggedInUser $d.ValueType.IsString $d.ValueType.IsDidFormat }}
              {{ template "assignToMeButton" (dict "def" $d "user" $.LoggedInUser "groupSuffix" $groupSuffix) }}
            {{ end }}
          {{ else if $d.ValueType.IsEnum }}
            <!-- radio buttons -->
            {{ $isUsed := $state.ContainsLabel $k }}
            {{ range $variant := $d.ValueType.Enum }}
              <label class="{{$labelStyle}}">
                <input type="radio" name="{{ $fieldName }}" value="{{$variant}}" {{if $state.ContainsLabelAndVal $k $variant}}checked{{end}}>
                {{ $variant }}
              </label>
            {{ end }}
            <label class="{{$labelStyle}}">
              <input type="radio" name="{{ $fieldName }}" value="" {{ if not $isUsed }}checked{{ end }}>
              None
            </label>
          {{ else }}
            <!-- single input field based on value type -->
            {{ range $v, $s := $valset }}
              {{ template "valueTypeInput" (dict "def" $d "value" $v "key" $k "prefix" $prefix) }}
            {{ else }}
              {{ template "valueTypeInput" (dict "def" $d "value" "" "key" $k "prefix" $prefix) }}
            {{ end }}
          {{ end }}
      </div>
    {{ end }}
  {{ end }}
{{ end }}

{{ define "multipleInputField" }}
  <div class="flex gap-1 items-stretch">
    <div class="flex-1 min-w-0">
      {{ template "valueTypeInput" . }}
    </div>
    {{ template "removeFieldButton" }}
  </div>
{{ end }}

{{ define "assignToMeButton" }}
  {{ $def := .def }}
  {{ $user := .user }}
  {{ $groupSuffix := .groupSuffix }}
  {{ $handle := trimPrefix (resolve $user.Did) "@" }}
  <button type="button"
    data-assign-to-me="{{ $def.Id }}{{ $groupSuffix }}"
    data-handle="{{ $handle }}"
    onclick="(() => {
      const group = document.getElementById('label-' + this.dataset.assignToMe);
      const handle = this.dataset.handle;
      const inputs = group.querySelectorAll('input[type=text]');
      const empty = Array.from(inputs).find(i => !i.value.trim());
      if (empty) { empty.value = handle; return; }
      if (Array.from(inputs).some(i => i.value.trim() === handle)) return;
      const tpl = document.getElementById('tpl-' + this.dataset.assignToMe);
      if (!tpl) return;
      const addBtn = tpl.nextElementSibling;
      addBtn.insertAdjacentHTML('beforebegin', tpl.innerHTML);
      const newInput = addBtn.previousElementSibling.querySelector('input[type=text]');
      if (newInput) newInput.value = handle;
    })()"
    class="text-xs text-gray-500 dark:text-gray-400 hover:underline self-end inline-flex items-center gap-1">
    {{ i "user-round-plus" "size-3.5" }}
    Assign to me
  </button>
{{ end }}

{{ define "addFieldButton" }}
  {{ $def := .def }}
  {{ $prefix := .prefix }}
  {{ $groupSuffix := .groupSuffix }}
  <div style="display:none" id="tpl-{{ $def.Id }}{{ $groupSuffix }}">
    {{ template "multipleInputField" (dict "def" $def "value" "" "key" $def.AtUri.String "prefix" $prefix) }}
  </div>
  <button type="button" onClick="this.insertAdjacentHTML('beforebegin', document.getElementById('tpl-{{ $def.Id }}{{ $groupSuffix }}').innerHTML)" class="w-full btn flex items-center gap-2">
    {{ i "plus" "size-4" }} Add
  </button>
{{ end }}

{{ define "removeFieldButton" }}
  <button type="button" onClick="this.parentElement.remove()" class="btn flex items-center gap-2 text-red-400 dark:text-red-500">
    {{ i "trash-2" "size-4" }}
  </button>
{{ end }}

{{ define "valueTypeInput" }}
  {{ $def := .def }}
  {{ $valueType := $def.ValueType }}
  {{ $value := .value }}
  {{ $key := .key }}

  {{ if $valueType.IsBool }}
    {{ template "boolTypeInput" $ }}
  {{ else if $valueType.IsInt }}
    {{ template "intTypeInput" $ }}
  {{ else if $valueType.IsString }}
    {{ template "stringTypeInput" $ }}
  {{ else if $valueType.IsNull }}
    {{ template "nullTypeInput" $ }}
  {{ end }}
{{ end }}

{{ define "boolTypeInput" }}
  {{ $def := .def }}
  {{ $prefix := .prefix }}
  {{ $fieldName := $def.AtUri.String }}
  {{ if $prefix }}{{ $fieldName = printf "%s[%s]" $prefix $def.AtUri }}{{ end }}
  {{ $value := .value }}
  {{ $isOn := eq $value "true" }}
  <label class="font-normal normal-case flex items-center gap-2">
    <input type="checkbox" name="{{ $fieldName }}" value="true" {{ if $isOn }}checked{{ end }}>
    {{ $def.Name }}
  </label>
{{ end }}

{{ define "intTypeInput" }}
  {{ $def := .def }}
  {{ $prefix := .prefix }}
  {{ $fieldName := $def.AtUri.String }}
  {{ if $prefix }}{{ $fieldName = printf "%s[%s]" $prefix $def.AtUri }}{{ end }}
  {{ $value := .value }}
  <input class="p-1 w-full" type="number" name="{{$fieldName}}" value="{{$value}}">
{{ end }}

{{ define "stringTypeInput" }}
  {{ $def := .def }}
  {{ $prefix := .prefix }}
  {{ $fieldName := $def.AtUri.String }}
  {{ if $prefix }}{{ $fieldName = printf "%s[%s]" $prefix $def.AtUri }}{{ end }}
  {{ $valueType := $def.ValueType }}
  {{ $value := .value }}

  {{ if $valueType.IsDidFormat }}
    {{ $value = trimPrefix (resolve .value) "@" }}
    <actor-typeahead>
      <input
        autocapitalize="none"
        autocorrect="off"
        autocomplete="off"
        placeholder="user.tngl.sh"
        value="{{$value}}"
        name="{{$fieldName}}"
        type="text"
        class="p-1 w-full h-full text-sm"
      />
    </actor-typeahead>
  {{ else }}
    <input class="p-1 w-full" type="text" name="{{$fieldName}}" value="{{$value}}">
  {{ end }}
{{ end }}

{{ define "nullTypeInput" }}
  {{ $def := .def }}
  {{ $prefix := .prefix }}
  {{ $fieldName := $def.AtUri.String }}
  {{ if $prefix }}{{ $fieldName = printf "%s[%s]" $prefix $def.AtUri }}{{ end }}
  <input class="p-1" type="hidden" name="{{$fieldName}}" value="null">
{{ end }}

{{ define "editLabelPanelActions" }}
  <div class="flex gap-2 pt-2">
    <button
      id="cancel-btn"
      type="button"
      hx-get="/{{ .RepoInfo.FullName }}/label"
      hx-vals='{"subject": "{{.Subject}}"}'
      hx-swap="outerHTML"
      hx-target="#edit-label-panel"
      class="btn w-1/2 flex items-center gap-2 text-red-500 hover:text-red-700 dark:text-red-400 dark:hover:text-red-300 group">
      {{ i "x" "size-4" }} Cancel
    </button>

    <button
      id="save-btn"
      type="submit"
      class="btn w-1/2 flex items-center">
      <span class="inline-flex gap-2 items-center">{{ i "check" "size-4" }} Save</span>
      <span id="spinner" class="group">
        {{ i "loader-circle" "ml-2 w-4 h-4 animate-spin hidden group-[.htmx-request]:inline" }}
      </span>
    </button>
  </div>
{{ end }}
