<script lang="ts">
  import {KEYMAP_CODES, KEYMAP_IDS} from "$lib/serial/keymap-codes"
  import type {ChordInfo} from "$lib/undo-redo"
  import {changes, ChangeType} from "$lib/undo-redo"

  export let chord: ChordInfo

  let pressedKeys = new Set<number>()
  let editing = false

  function edit() {
    pressedKeys = new Set()
    editing = true
  }

  function keydown(event: KeyboardEvent) {
    if (!editing) return
    event.preventDefault()
    pressedKeys.add(KEYMAP_IDS.get(event.key)!.code)
    pressedKeys = pressedKeys
  }

  function keyup() {
    if (!editing) return
    editing = false
    if (pressedKeys.size < 2) return
    changes.update(changes => {
      changes.push({
        type: ChangeType.Chord,
        id: chord.id,
        actions: [...pressedKeys],
        phrase: chord.phrase,
      })
      return changes
    })
  }
</script>

<button
  class:deleted={chord.phrase.length === 0}
  class:edited={chord.actionsChanged}
  on:click={edit}
  on:keydown={keydown}
  on:keyup={keyup}
>
  {#if editing && pressedKeys.size === 0}
    <span>Press keys</span>
  {/if}
  {#each editing ? [...pressedKeys].sort() : chord.actions as actionId}
    {@const {icon, id, code} = KEYMAP_CODES[actionId] ?? {code: actionId}}
    <kbd class:icon={!!icon}>
      {icon ?? id ?? `0x${code.toString(16)}`}
    </kbd>
  {/each}
  <sup>•</sup>
</button>

<style lang="scss">
  span {
    opacity: 0.5;
  }

  sup {
    translate: 0 -60%;
    opacity: 0;
    transition: opacity 250ms ease;
  }

  button {
    position: relative;

    display: inline-flex;
    gap: 4px;

    height: 32px;
    margin-inline: 4px;

    &:focus-within {
      outline: none;
    }
  }

  kbd {
    height: 24px;
    padding-block: auto;
    transition: color 250ms ease;
  }

  button::after {
    content: "";

    position: absolute;
    top: 50%;
    transform-origin: center left;
    scale: 0 1;

    width: calc(100% - 16px);
    height: 1px;

    background: currentcolor;

    transition:
      scale 250ms ease,
      color 250ms ease;
  }

  .edited {
    color: var(--md-sys-color-primary);

    & > sup {
      opacity: 1;
    }
  }

  .deleted {
    color: var(--md-sys-color-error);

    &::after {
      scale: 1;
    }
  }
</style>
