<script setup>
import { nextTick, ref, watch } from 'vue'
import ModalDialog from './ModalDialog.vue'
import { useSaveFilePrompt } from '../composables/useSaveFilePrompt.js'

const { pendingSave, confirmFilename, cancelFilename } = useSaveFilePrompt()

const stem = ref('')
const inputRef = ref(null)

watch(pendingSave, async (save) => {
  if (!save) return
  stem.value = save.defaultStem
  await nextTick()
  inputRef.value?.focus()
  inputRef.value?.select()
})

function onSave() {
  confirmFilename(stem.value)
}
</script>

<template>
  <ModalDialog v-if="pendingSave" :title="$t('saveFile.title')" @close="cancelFilename">
    <label class="save-file-label" for="save-file-input">{{ $t('saveFile.label') }}</label>
    <div class="save-file-input-row">
      <input
        id="save-file-input"
        ref="inputRef"
        v-model="stem"
        type="text"
        class="save-file-input"
        data-testid="save-file-input"
        @keydown.enter="onSave"
      />
      <span class="save-file-extension" data-testid="save-file-extension">{{
        pendingSave.extension
      }}</span>
    </div>
    <div class="save-file-actions">
      <button class="btn" data-testid="save-file-cancel" @click="cancelFilename">
        {{ $t('saveFile.cancel') }}
      </button>
      <button class="btn btn-primary" data-testid="save-file-confirm" @click="onSave">
        {{ $t('saveFile.save') }}
      </button>
    </div>
  </ModalDialog>
</template>

<style scoped>
.save-file-label {
  display: block;
  font-size: 13px;
  color: var(--front-color2);
  margin-bottom: 6px;
}

.save-file-input-row {
  display: flex;
  align-items: center;
  gap: 4px;
}

.save-file-input {
  flex: 1;
  min-width: 0;
}

.save-file-extension {
  color: var(--front-color2);
  white-space: nowrap;
}

.save-file-actions {
  display: flex;
  justify-content: flex-end;
  gap: 8px;
  margin-top: 16px;
  padding-top: 16px;
  border-top: 1px solid var(--border-color);
}
</style>
